Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_many :through with conditions and building associations

I'm having problems building an association that is a has_many :through with conditions. I have this model:

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

problem happens when I try to instantiate a group from a contact. With the above syntax, I get an error:

contact.groups.build
=> ActiveRecord::UnknownAttributeError: unknown attribute: groups

But when I use the following syntax it works:

has_many :groups, :through => :group_contacts, :conditions => ['groups.published = ?', true]

contact.groups.build
=> #<Group id: nil, name: nil, description: nil, created_at: nil, updated_at: nil, published: true>

I see a reference to the exact problem in this question. It is said a ticket would be filed for this bug (back in pre- rails 3 versions). I can't find anything however on rails 3.0.x.

I'm using 3.0.8. Has anyone else found this issue?

Further Notes:

I've also found that when I'm building groups, it actually ignores my conditions on the association when building. The only reason my above build had published => true is because it's the default in the db.

This seems like a regression, can anyone else verify this?

like image 359
brad Avatar asked Aug 15 '11 16:08

brad


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is self association in Rails?

Self-referential association is used to associate a model with itself. The most frequent example would be, to manage association between a friend and his follower. ex. rails g model friendship user_id:references friend_id:integer.


1 Answers

has_many :groups, :through => :group_contacts, :conditions => {:published => true}

or

has_many :groups, :through => :group_contacts, :conditions => {"groups.published" => true}
like image 135
fl00r Avatar answered Sep 27 '22 19:09

fl00r