I have something like this:
class Suite < ActiveRecord::Base
has_many :tests
end
class Test < ActiveRecord::Base
belongs_to :suite
end
And I'm using the cache_digests gem to do fragment caching.
I want that when I update a Suite object, the children tests caches expire.
I tried to put a touch: true
in the has_many
association without success.
How can I do that?
Thanks in advance
EDIT
I was doing my cache like this:
<% cache test do %>
<tr>
etc...
<% cache test.suite do %>
etc..
<% end %>
</tr>
<% end %>
But it doesn't work, because when I edit a suite, their tests isn't touched. So, I changed my cache declaration to something like this:
<% cache [test, test.suite] do %>
etc..
<% end %>
And it worked just as expected.
When I edit a test, or a suite, one of those is touched, so, the fragment got expired and I got the new version just as expected.
Thanks to @taryn-east for the help.
You're right,
touch: true
doesn't work onhas_many
relationships. You could use anafter_save
hook and update all the associated assets manually. For example...WARNING: This will bypass ActiveRecord when updating the assets, so if the assets need to in turn touch another object, this won't work. You could however put some extra logic into the
touch_assets
method that updates the objects that the assets were supposed to update. But this starts to get messy.you need to add
on the has_many association if you want to force parents updating children. touch is used for updating child -> parent.
This page: https://github.com/rails/rails/issues/8759
Suggest using an after_save hook:
try this
Change your fragment cache strategy, use something like:
I found this answer in the comments. I just want to make it obvious this is "the answer."