This project is archived and is in readonly mode.
count(:id, :distinct => true) as default
Reported by Greg Hazel | December 10th, 2009 @ 02:03 AM
When joining with other tables, it is often wrong to use .count() to get the number of records. For example when trying to count the number of users who have posts:
User.scoped(:joins => :posts).count
Gives a count of all the posts, since it's counting rows returned by the DB. However, the query was built on User, so one would expect the count to be related to the number of Users. For example these are equivalent:
User.scoped(:joins => :posts).count
Post.scoped(:joins => :user).count
This query does the right thing, which is counting the number of users who have posts:
User.scoped(:joins => :posts).count(:id, :distinct => true)
So, it seems like .count() should maybe default to using "(:id, :distinct => true)", with the option to say :distinct => false, etc, instead of the other way around.
Comments and changes to this ticket
-
Rohit Arondekar October 7th, 2010 @ 12:05 PM
- State changed from new to stale
- Importance changed from to Low
Marking ticket as stale. If this is still an issue please leave a comment with suggested changes, creating a patch with tests, rebasing an existing patch or just confirming the issue on a latest release or master/branches.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>