Reputation: 6612
Until now I used uniq_by
to count unique projectusers. But this method has been deprecated and the suggestion is to use uniq
instead. But uniq_by
returns 2 (correct!) and uniq
returns 3 (not correct). The projectuser table is filled like this:
id,user_id
1,1
2,1
3,2
And here are the statements:
Projectuser.uniq_by {|p| p.user_id}.count --> 2
Projectuser.uniq {|p| p.user_id}.count --> 3
What do I need to change?
Upvotes: 1
Views: 205
Reputation: 22296
The result is rigth, since uniq
is from Array. To match the uniqueness in SQL idiom you need to use distinct.
From the example from the documentation:
person.pets.select(:name).distinct
# => [#<Pet name: "Fancy-Fancy">]
Try:
Projectuser.select(:id, :user_id).distinct
Upvotes: 0
Reputation: 3880
The ActiveReord-Version of uniq seem to ignore the given block, and just check that the objects are uniq. If you look at the source you see that is just sets a flag.
See http://apidock.com/rails/ActiveRecord/QueryMethods/uniq
You can think of it as a modifier for the generated sql-statement.
Upvotes: 1