This project is archived and is in readonly mode.

#6678 new

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

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

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

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(" != 42").count
  SQL (0.2ms)  SELECT COUNT(*) FROM "posts" INNER JOIN "comments" ON "posts".id = "comments".post_id WHERE (("comments".user_id = 1)) AND ( != 42)
=> 2

but only when count - all works as expected:

ruby-1.9.2-p0 > user.commented_posts.where(" != 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 ( != 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=""></a>

People watching this ticket