Tip: Nested attributes need a reload before you can trust them

I hit on a solution (probably well known by others) that needs repeating so it can be found by Google next time :sunglasses:

I am using Ryan Bates' nested_form Gem, which works perfectly to create rich nested forms with extra JavaScript goodies like "Add another [nested object]". In my controller's update method, I was testing to see if the result of the update had left a Title with no "primary" Person, using this bit of logic:

if((@title.roles.length > 0) && !@title.roles.include?( @title.role ))    @title.update_attributes(:role_id => @title.roles.first.id) end

I put this block after the @title.update_attributes(params[:title]) call, and spent most of the afternoon chasing my tail to figure out why it never was working. A puts @title.roles.inspect showed that the list of roles apparently hadn't been changed by the call to update_attributes, even though the following page load (to the view method) showed the correct data had been persisted.

This morning, I added the line

@title.reload

before the block, and all started working perfectly. So word to the wise, reload before you start asking questions!

Walter