8

是否可以让named_scope某个列的返回记录唯一?

例如

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

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

所以["style 1", "style 1", "style 1"]不可能,它会强迫自己付出["style 1", "some style 2", "maybe another 3"]

  • 我认为group可以这样做,我现在正在使用它。如果有人有任何意见,无论如何都会很棒。
4

3 回答 3

13

您可能想探索finders 和named_scopes 的 :group 选项:

named_scope :unique_styles, :order => "title desc", :limit => 3, :group => "title"
于 2010-01-14T00:28:04.937 回答
3

对于 Rails 3 窥视,您可以使用菊花链样式:

scope :unique_styles, order("title DESC")
                      .select("DISTINCT title")
                      .limit(3)
于 2012-02-08T06:10:00.743 回答
2

如果你真正想要的只是标题,这应该为 MySQL 做。(我没有调查其他引擎是否支持 DISTINCT。)

named_scope :unique_styles, :select => 'DISTINCT title', :order => 'title desc', :limit => 3
于 2010-01-14T00:28:41.097 回答