0

I have an Artists model with name:string and other attributes. BUT I have multiple Artist entries under the SAME name.

Is there a way to pull an array of artist objects without any duplicates of name?

I've found ways to do with with only the name attribute but nothing where I can get the entire artist object.

These both do just the name attribute:

@artists = Artist.select('DISTINCT name').all
@artists = Artist.all.collect{ |a| a.name }.uniq

3 Answers 3

2

Activerecord group does what you're looking for: Artist.group(:name).all

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice thanks, I give this the answer because it benchmarks 50% better than the above answer. Thanks.
0

My rails 3 is not so good but it still has rails 2 syntax.

@artists = Artist.find(:all, :select => 'DISTINCT name')

And then we can get some rails 3 love.

2 Comments

maybe be too outdated, I get: ArgumentError: Unknown key(s): distinct
I think thats the same as what I did above, it returns [#<Artist name: "jeff">, #<Artist name: "jim hendrix">] but not the entire artist object, or am I missing something?
0

One way is to grab the ids of distinct rows and grab the rest of the data from there:

Artist.where('artists.id IN (SELECT MIN(a.id) FROM artists AS a GROUP BY a.name)').all

2 Comments

Hi this does look to be completing what I was looking for, could you explain a little more whats happening and how many requests there are?
It first groups everything by name (duplicate names are all in 1 group) and grabs the lowest id from those groups (the inner select) and then grabs all artists with those ids. It's still just 1 sql query but the database does a bit more processing to avoid duplicates. Be sure to have an index on the name column. You might want to consider preventing duplicate artists in the first place if you are always ignoring them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.