has_many setter should set conditions if specified

I'm not sure how to think about this experience with has_many association

Suppose we have:

class User < ActiveRecord::Base   has_many :awesome_friends, :class_name => "Friend", :conditions => {:awesome => true} end

(as well as the belongs_to in Friend class)

And execute the code:

my_user.awesome_friends << Friend.new(:name=>'jim')

Afterwards, when I inspect this friend object, I see that the user_id field is populated. But I would also expect to see the "awesome" column set to 'true', which it is not.

Furthermore, if I execute the following from the console:

my_user.awesome_friends << Friend.new(:name=>'jim') my_user.awesome_friends

= [#<Friend id:1, name:"jim", awesome:nil>] # Quit and restart the console

my_user.awesome_friends

=

Any thoughts on this? I suppose the conditions hash could be arbitrarily complex, making integration into the setter impossible. But in a way it feels like by default we are passing the condition ":user_id => self.id", and that gets set, so shouldn't others?

Thanks, Mike

Hi Mike,

The << operator calls concat on the association which adds an existing object without modifying it (except the foreign key). This is by design. If you use the create or build methods instead you should find that the conditions are set as you would expect provided that you continue to use hash style conditions.

my_user.awesome_friends.create(:name => 'jim')

- Matt

If you're building a new object, you can get this behavior by using build:

new_friend = my_user.awesome_friends.build(:name => 'Jim')

new_friend will have awesome set to true.

Note that this only works for associations with hash conditions; there's not a reasonable way to turn something like:

:conditions => 'some_field IS NOT NULL'

into a setter.

--Matt Jones