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 query with :include generates incorrect SQL

#3585

Executing certain ActiveRecord count queries with an :include option provided generates incorrect SQL. For example:

>> Thing.count('widgets.bar_id', :distinct => true, :conditions=>"frobs.name = 'asdf'", :include=>[:widget, :frob])
  SQL (0.4ms)   SELECT count(DISTINCT "things".id) AS count_widgets_bar_id FROM "things" LEFT OUTER JOIN "widgets" ON "widgets".id = "things".widget_id LEFT OUTER JOIN "frobs" ON "frobs".id = "things".frob_id WHERE (frobs.name = 'asdf') 
=> 10

In summary:
"Thing.count('widgets.bar_id', :distinct => true," is somehow getting turned into "SELECT count(DISTINCT "things".id)" and leading to incorrect results.

Note: when a :joins is used instead, everything is as expected.

>> Thing.count('widgets.bar_id', :distinct => true, :conditions=>"frobs.name = 'asdf'", :joins=>[:widget, :frob])
  SQL (0.2ms)   SELECT count(DISTINCT widgets.bar_id) AS count_widgets_bar_id FROM "things" INNER JOIN "widgets" ON "widgets".id = "things".widget_id INNER JOIN "frobs" ON "frobs".id = "things".frob_id WHERE (frobs.name = 'asdf') 
=> 1

(which is correct)

This happens on Rails 2.3.4 and 2.3.5. The rails project is attached.

Reported by Brian Moore · December 16th, 2009 @ 07:58 PM

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:06 PM