This project is archived and is in readonly mode.
size method ignores "group by" on has_many
Reported by matthewgarysmith (at gmail) | August 29th, 2008 @ 09:26 PM | in 2.x
A has_many that uses the :group option, returns invalid results for the size method.
class Book < ActiveRecord::Base
has_many :reviews
has_many :reviewers, :through => :reviews, :group => "reviews.id"
end
class Review < ActiveRecord::Base
belongs_to :book
belongs_to :reviewer
end
class Reviewer < ActiveRecord::Base
has_many :reviews
has_many :books, :through => :reviews, :group => "books.id"
end
After create a bunch of reviews...
alan = Reviewer.find_by_name("alan")
alan.books.size # => 4
alan.books.to_a.size # => 2
This is the SQL generated by the second line ignores the :group option:
SELECT count(*) AS count_all FROM "books" INNER JOIN reviews ON books.id = reviews.book_id WHERE (("reviews".reviewer_id = 1))
it should be more like the follow, no?
SELECT count(distinct books.id) AS count_all FROM "books" INNER JOIN reviews ON books.id = reviews.book_id WHERE (("reviews".reviewer_id = 1))
Attached are detailed steps to reproduce the bug.
Comments and changes to this ticket
-
Assaf Arkin September 10th, 2008 @ 08:42 PM
I'm pretty sure this used to work before, 2.1.0 and edge.
-
Emilio Tagua September 12th, 2008 @ 04:11 PM
- Tag changed from activerecord, bug, has_many to activerecord, bug, has_many, patch
Here is the patch to fix this, includes a test to verify that the :group option is included when the target hasn't been loaded.
-
Emilio Tagua September 15th, 2008 @ 05:25 PM
- no changes were found...
-
Repository September 15th, 2008 @ 05:33 PM
- State changed from new to committed
(from [dc8bf7515de85f5bc28d17e96edf4a3e74a858da]) When counting grouped records the target should be loaded to return a valid groups count result.
Without this change count_records will group for the count in the query and return erroneous results.
Signed-off-by: Michael Koziarski michael@koziarski.com [#937 state:committed] http://github.com/rails/rails/co...
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>
People watching this ticket
Attachments
Tags
Referenced by
- 937 size method ignores "group by" on has_many Signed-off-by: Michael Koziarski michael@koziarski.com [#...