Named_scope in rails unique records?
Asked Answered
S

3

8

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.
Seashore answered 14/1, 2010 at 0:25 Comment(0)
T
13

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

named_scope :unique_styles, :order => "title desc", :limit => 3, :group => "title"
Timaru answered 14/1, 2010 at 0:28 Comment(1)
It's ":group" not ":group_by" figured this out and it worked, thanks!Seashore
A
3

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

scope :unique_styles, order("title DESC")
                      .select("DISTINCT title")
                      .limit(3)
Assumptive answered 8/2, 2012 at 6:10 Comment(0)
W
2

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
Wildebeest answered 14/1, 2010 at 0:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.