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:
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?
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.
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.
If you’re building a new object, you can get this behavior by using
build: