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.

has_many through with uniq gives wrong count if condition given

#6678

Affects rails 3, including current master.

Here is a sample model setup:

class Post < ActiveRecord::Base  
  has_many :comments
end

class Comment < ActiveRecord::Base  
  belongs_to :post
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :comments
  has_many :commented_posts, through: :comments, source: :post, uniq: true
end

Now the following works correctly:

ruby-1.9.2-p0 > user.commented_posts.count
  SQL (0.2ms)  SELECT COUNT(DISTINCT "posts".id) FROM "posts" INNER JOIN "comments" ON "posts".id = "comments".post_id WHERE (("comments".user_id = 1))
=> 1

But adding condition makes active record 'forget' about uniq: true bit:

ruby-1.9.2-p0 > user.commented_posts.where("posts.id != 42").count
  SQL (0.2ms)  SELECT COUNT(*) FROM "posts" INNER JOIN "comments" ON "posts".id = "comments".post_id WHERE (("comments".user_id = 1)) AND (posts.id != 42)
=> 2

but only when count - all works as expected:

ruby-1.9.2-p0 > user.commented_posts.where("posts.id != 42").all
  Post Load (0.3ms)  SELECT DISTINCT "posts".* FROM "posts" INNER JOIN "comments" ON "posts".id = "comments".post_id WHERE (("comments".user_id = 1)) AND (posts.id != 42)
=> [#<Post id: 1, created_at: "2011-03-07 12:17:30", updated_at: "2011-03-07 12:17:30">]

Reported by artemave · April 6th, 2011 @ 10:33 AM

State: new
Milestone: none
Assigned to: nobody
Importance: none