Pete
Pete

Reputation: 1482

Rails fragment caching strategy

I've got a site i'm implementing some caching into.

Where possible, i have used action caching and i have sweepers in place to expire the necessary actions when models are created/updated.

Within the views that are subject to caches_action i have also fragment cached some partials so that within the partial i have something like:

<% cache('video_content') do %>
   Some content here
<% end %>

In my video_sweeper i am trying to expire this fragment with:

expire_fragment('video_content')

This fragment isn't expiring though.

Because i am using caches_action already, is the fragment being ignored for some reason? i.e do i need to make a choice between using caches_action or fragment caching?

If this is the case, i would need to expire every action view this partial appears in which means my sweepers are going to get hellishly complicated, let alone the maintenance headache.

So my question is largely, why won't my fragment cache expire when called from my sweeper and is it because i am using caches_action too?

Update: Further digging into my logs i can actually see that the sweeper is expiring my fragment.

Expire fragment views/video_content (0.7ms)

However, playing around in the console prior to the expiration, the fragment doesn't seem to exist.

ruby-1.9.2-p136 :004 > Rails.cache.exist?('views/video_content')
 => false

Again, this makes me think that because i am using caches_action that the partial will rarely be hit, except when the action is expired, to be cached.

Upvotes: 0

Views: 1540

Answers (2)

Ross
Ross

Reputation: 1562

Action caching will cache the complete action for you. So using an action caching on a controller action (say 'show_video') and adding a fragment caching on the same view "show_video" will not have much effect.You should use them wisely.

Futher as you said the fragment caching expires but when the action is called the cached action is rendered. So in your case you need to expire you action cache as well.

I would suggest you to go through the video casts by Greg Pollack check this out

Upvotes: 0

onknows
onknows

Reputation: 6681

Action caching is also technically type of fragment caching which wraps your fragment. So your fragment might expire but this will not be visible untill the action cache expires.

So if want your fragment to expire you need to expire the action as well. But the fragment caching is not without purpose. If the action expires, the cached fragment will be used.

Upvotes: 1

Related Questions