Skip to content

ActiveRecord #build_association Does Not Construct a New Object

I learned valuable tidbit about belongs_to and #build_association: if there is already an associated object, a new one isn’t constructed.

Let’s consult the docs:

build_association(attributes = {})
Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key, but has not yet been saved.

It says it “[r]eturns a new object of the associated type,” but that’s only true if the association is nil. If there is already an associated object, it just sets all the attributes to nil.

Let’s check it out:

example_app $ rails console
Loading development environment (Rails 3.0.10)
1.8.7 :001 > note = Note.find(2)
 => #<Note id: 2, account_id: 42444, note_text: "Magni et soluta repellendus voluptatem placeat volu...", ...> 
1.8.7 :002 > orig_account = note.account
 => #<Account id: 42444, dba_name: "Spinka, Conroy and Emmerich", ...> 
1.8.7 :003 > orig_account.object_id
 => 2207807220 
1.8.7 :004 > note.build_account
 => #<Account id: nil, dba_name: nil, ...> 
1.8.7 :005 > orig_account
 => #<Account id: nil, dba_name: nil, ...> 
1.8.7 :006 > note.account.object_id
 => 2207807220 
1.8.7 :007 > 

Fun, huh? Fortunately, it’s not too difficult to work around, simply construct your own object, *but* don’t forget to add the association by foreign key!

Posted in Rails, Ruby, Software Development, Tips and Tricks.

Tagged with .

One Response

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Tim Liner says

    I was running into this problem too. In the current version of Rails (3.2.8), though, I think the original associated object is actually deleted, which is way more fun!

Some HTML is OK

or, reply to this post via trackback.