Named_scope中的rails唯一记录?

是否可以使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可能会这样做,而我现在正在使用它。 如果有人有任何评论,不管这是伟大的。

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

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

对于Rails 3 peeps,你可以做菊花链式:

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

如果你想要的只是标题,那么这就是为MySQL做的。 (我没有考虑其他引擎是否支持DISTINCT。)

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