ruby-on-railscachingfragment-caching

Does Rails' fragment caching suit this problem?


I do not understand yet Rails' caching system, but I've read in the guides section of a feature called fragment caching.

My problem is: my view consist mostly in static elements. It is almost completely static, the only changing is a status message and a hidden input field in a form, both generated at every request to the action serving the view.

Is fragment caching suitable for this problem? What caching strategy should I use?


Solution

  • Fragment caching is adequate to your problem. It is adequate because it enables you to cache a part (fragment) of your view, instead of the whole view. From the docs:

    Fragment caching is used for caching various blocks within templates without caching the entire action as a whole. This is useful when certain elements of an action change frequently or depend on complicated state while other parts rarely change or can be shared amongst multiple parties. The caching is done using the cache helper available in the Action View. A template with caching might look something like:

    <!-- this is the dynamic part-->
    <b>Hello <%= @name %></b>
    
    <% cache do %>
      <%= render :partial => "static_part" %>
    <% end %>
    

    So you can put your static part between the cache block, and the dynamic part outside of it. Here's the link to the relevant docs: rails fragment caching.