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.