Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

count(:id, :distinct => true) as default

#3557

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.

Reported by Greg Hazel · December 10th, 2009 @ 02:03 AM

State: stale
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Rohit Arondekar
    Rohit Arondekar
    • 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.

    October 7th, 2010 @ 12:05 PM

  2. bingbing