This project is archived and is in readonly mode.

#6678 new
artemave

has_many through with uniq gives wrong count if condition given

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

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">]

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>

People watching this ticket

Pages