This morning I encountered a weird problem with a has_many association. Consider the following example:
class User < AR:Base
has_many :email_addresses
def email= (address)
email_addresses.build(:address => address)
end
end
class EmailAddress < AR:Base
belongs_to :user
end
I use User#email= to create an initial email address record for each user created. It works fine, except if you access User#email_addresses on non-saved user records:
# Works fine (creates user record and associated email address record):
User.create!(:username=>'foo', :email=>'foo@bar.baz')
# Also works fine:
u = User.new(:username=>'foo', :email=>'foo@bar.baz')
u.save!
# Does NOT work (user record saved, email address record lost):
u = User.new(:username=>'foo', :email=>'foo@bar.baz')
u.email_addresses # => []
u.save!
Is this a bug or intended behaviour? It looks like the has_many collection cache does not recognize associated objects that are build during initialization.
I posted a more detailled story in my blog.