Posted about 4 years ago. Visible to the public. Repeats.

How to discard ActiveRecord's association cache

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.

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

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

Copy
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:

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

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 4 years ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more