Rails中的named_scope唯一记录?
是否可以让 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能想探索查找器和named_scopes的:group选项:
You probably want to explore the :group option for finders and named_scopes:
对于 Rails 3,你可以采用菊花链方式:
For Rails 3 peeps you can do it daisy-chain style:
如果你真的想要的只是标题,这应该可以为 MySQL 做到。 (我还没有研究其他引擎是否支持 DISTINCT。)
If really all you want is the titles, this oughta do it for MySQL. (I haven't looked into whether other engines support DISTINCT.)