This project is archived and is in readonly mode.

#937 ✓committed
matthewgarysmith (at gmail)

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

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>

Referenced by

Pages