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.

size method ignores "group by" on has_many

#937

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.

Reported by matthewgarysmith (at gmail) · August 29th, 2008 @ 09:26 PM

State: committed
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Assaf Arkin
    Assaf Arkin

    I'm pretty sure this used to work before, 2.1.0 and edge.

    September 10th, 2008 @ 08:42 PM

  2. Emilio Tagua
    Emilio Tagua
    • 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.

    September 12th, 2008 @ 04:11 PM

  3. Emilio Tagua
  4. Repository
    Repository
    • 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 size method ignores "group by" on has_many state:committed] http://github.com/rails/rails/co...

    September 15th, 2008 @ 05:33 PM