This project is archived and is in readonly mode.

#3585 ✓stale
Brian Moore

Count query with :include generates incorrect SQL

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

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

>> Thing.count('widgets.bar_id', :distinct => true, :conditions=>" = '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 ( = '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=>" = '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 ( = 'asdf') 
=> 1

(which is correct)

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

Comments and changes to this ticket

  • Rohit Arondekar

    Rohit Arondekar October 7th, 2010 @ 12:06 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=""></a>