Friday, March 14, 2014

Rails: updating an association through nested attributes does not touch the owner

I was a little surprised to discover that when you update an association through nested attributes, it won't touch the parent record.  It makes sense when you consider that Rails is optimizing by not writing records that have not changed, but if were using updated_at on the model for caching you may be surprised.

For instance:

With these models:


This code will not change updated at on the post record:

As shown in the log:

The fix is very simple. Just touch the post record from the comment if you need updated_at to change on posts.

And now our post is updated:

Of course there are other ways to do this...

The code for this is on github.

1 comment:

  1. It is worth mentioning the `:touch => true` option on ActiveRecord associations (see http://guides.rubyonrails.org/association_basics.html#touch), which should behave just like the before_save and before_destroy callbacks you are using.

    ReplyDelete