rails has_many :through with conditions on aliased association-Collection of common programming errors

This kind of goes along with my original question about has_many :through with conditions, but I’ve found another problem.

Given this class:

class Contact < AR
  has_many :group_contacts
  has_many :groups, :through => :group_contacts, :conditions => {:published => true}
  has_many :anonymous_groups, :through => :group_contacts, :source => :group, :conditions => {:anonymous => true}
end

My problem happens when I try to include the anonymous_groups with contacts:

Contact.includes(:anonymous_groups)

ActiveRecord::StatementInvalid: PGError: ERROR: missing FROM-clause entry for table “contacts”

The reason for this is the generated sql is incorrect. It’s something akin to:

SELECT "group_contacts"."id" AS t0_r0 ... "groups"."anonymous" AS t1_r5 ... LEFT OUTER JOIN "groups" ON "groups"."id" = "group_contacts"."group_id" WHERE ("group_contacts".contact_id IN (...) AND ("contacts"."anonymous" = 'true'))

Paraphrased of course, but look at the final condition. It’s put the anonymous condition on contacts rather than groups

Now, we can alleviate this query error (which i’m sure is a bug) but doing something like:

has_many :anonymous_groups, :through => :group_challenges, :source => :group, :conditions => { :groups => {:anonymous => :true} }

This puts the condition on the correct table in sql, but when I try to build an anonymous group, I get this:

contact.anonymous_groups.build

ActiveRecord::UnknownAttributeError: unknown attribute: groups.anonymous

So it works for querying but not for building. I’m quite certain this is a bug, but I’m wondering if anyone else has experienced this or has a workaround.

  1. I think something like :conditions => "groups.anonymous = true" should work fine.

Originally posted 2013-11-09 23:12:02.