Rails中的named_scope唯一记录?

发布于 2024-08-17 23:33:44 字数 443 浏览 5 评论 0原文

是否可以让 named_scope 返回特定列的唯一记录?

例如,

named_scope :unique_styles, :order =>"title desc", :limit => 3

这将为我提供三种样式,但如果我想确保标题不同怎么办?在这种情况下,可能有三个具有相同样式的记录,我希望这个named_scope仅给出标题的唯一值。

所以 ["style 1", "style 1", "style 1"] 是不可能的,它会强制自己给出 ["style 1", "some style 2" ,“也许还有 3 个”]

  • 我认为 group 可以做到这一点,我现在正在使用它。如果有人有任何意见,那就太好了。

Is it possible to have named_scope return records unique for a certain column?

e.g

named_scope :unique_styles, :order =>"title desc", :limit => 3

That will give me three styles but what if I want to make sure the title is different? In this case there may be three records with the same style, I want this named_scope to only give unique values of title.

So ["style 1", "style 1", "style 1"] isn't possible, it'll force itself to give ["style 1", "some style 2", "maybe another 3"]

  • i think group may do it and I'm using that for now. If anyone has any comments regardless that'd be great.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

○闲身 2024-08-24 23:33:44

您可能想探索查找器和named_scopes的:group选项:

named_scope :unique_styles, :order => "title desc", :limit => 3, :group => "title"

You probably want to explore the :group option for finders and named_scopes:

named_scope :unique_styles, :order => "title desc", :limit => 3, :group => "title"
旧伤还要旧人安 2024-08-24 23:33:44

对于 Rails 3,你可以采用菊花链方式:

scope :unique_styles, order("title DESC")
                      .select("DISTINCT title")
                      .limit(3)

For Rails 3 peeps you can do it daisy-chain style:

scope :unique_styles, order("title DESC")
                      .select("DISTINCT title")
                      .limit(3)
旧城空念 2024-08-24 23:33:44

如果你真的想要的只是标题,这应该可以为 MySQL 做到。 (我还没有研究其他引擎是否支持 DISTINCT。)

named_scope :unique_styles, :select => 'DISTINCT title', :order => 'title desc', :limit => 3

If really all you want is the titles, this oughta do it for MySQL. (I haven't looked into whether other engines support DISTINCT.)

named_scope :unique_styles, :select => 'DISTINCT title', :order => 'title desc', :limit => 3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文