Skip to content

Instantly share code, notes, and snippets.

@scottwater
Created April 21, 2011 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottwater/935283 to your computer and use it in GitHub Desktop.
Save scottwater/935283 to your computer and use it in GitHub Desktop.
Site.joins(:user).select('sites.user_id, count(*) as count').group('sites.user_id')
<Site user_id: 1> #should have a count of 2
# returns only the user_id. If I cheat and name the 'count' column the same name as another column on my model it returned.
Site.joins(:user).select('sites.user_id, count(*) as id').group('sites.user_id') #BAD!
<Site id: 2, user_id: 1> #id == count in this result
@kevinansfield
Copy link

Each returned object should have a count attribute with the count assigned.

Testing locally:

User.joins(:favourites).select('users.id, count(*) as count').group('users.id').first.count
"3"

@scottwater
Copy link
Author

Hi Kevin,

That was the trick.

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment