Read more

How to discard ActiveRecord's association cache

Arne Hartherz
April 08, 2015Software engineer at makandra GmbH

You know that ActiveRecord caches associations so they are not loaded twice for the same object. You also know that you can reload an association to make Rails load its data from the database again.

user.posts.reload
# discards cache and reloads and returns user.posts right away
# => [...]
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

If you want to discard the cache but not query the database (only the next time the association is accessed), you can use reset:

user.posts.reset
# discards cache, but does not load anything yet
user.posts
# SQL query happens to load new state
# => [...]

Note that reset returns the association/scope.

Hence, the above will not seem to work on the Rails console, just because the return value is inspected and thus resolved right away.
Try it like this:

user.posts.reset; nil
# no query
user.posts
# query, and returns results

Tip

You can also reload or reset plain scopes ("relations") that are not also associations.

Posted by Arne Hartherz to makandra dev (2015-04-08 18:57)