Today I Learned

hashrocket A Hashrocket project

ActiveRecord Reload only Associated Record

Today I learned about some focused reload methods for ActiveRecord Associations.

Let's say I have an Author class that can have one magnum opus.

class Author < ApplicationRecord
  has_one :magnum_opus

Now suppose I've instantiated an Author, and his magnum opus gets updated elsewhere. If I try to access that instance's magnum opus again (existing instance, no reloading), I'll get the old cached version:

author = Author.first
author.magnum_opus.title # => "The Dark Tower"

mo = MagnumOpus.find_by(title: "The Dark Tower")
mo.update title: "The Shining"

author.magnum_opus.title # => "The Dark Tower"

Now to remedy this, we can reload the author:

author.reload.magnum_opus.title # => "The Shining"

But why reload the whole author when you can reload just the association? ActiveRecord has reload_* methods for each has_one and belongs_to association that does just that - it reloads only the associated record.

author.reload_magnum_opus.title # => "The Shining"

Docs for has_one and belongs_to.

h/t Matt Polito

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.