Reputation: 7708
I've this code:
User.joins(:pets).select('users.*, COUNT(pets.id) as pets_count').group('user.id')
That returns a User::ActiveRecord_Relation
. however I'm not able to fetch the value in the pets_count
column of the resultset.
How can I access to that value? or what can I use in order to have the count from a join?
Upvotes: 0
Views: 72
Reputation: 2624
The user in group should be users:
@users = User.joins(:pets).select('users.*, COUNT(pets.id) as pets_count').group('users.id')
You can get the pets_count without any problem when you call @users.first.pets_count
Upvotes: 1
Reputation: 47472
If you are looking into the console, you'll see only user's attributes but after iterating you can call 'pets_count' on it.
For Ex:-
users = User.joins(:pets).select('users.*, COUNT(pets.id) as pets_count').group('user.id')
users.each do |user|
user.pets_count
end
Upvotes: 1