Ruby on Rails form page caching including authenticity_token Ruby on Rails form page caching including authenticity_token ruby-on-rails ruby-on-rails

Ruby on Rails form page caching including authenticity_token


As Matchu posted, you could implement point two from this post (same link he posted, but found via my Googling as well). This adds a dependency on JavaScript, which may or may not be something you want.

Alternatively, you could look into Fragment Caching. This allows you to cache certain portions of a page, but still generate the dynamic portions (such as forms with authenticity tokens). Using this technique, you could cache the rest of the page, but generate a new form for every request.

One final solution (but the least favourable), is to disable the authenticity token for that specific action. You can do this by adding the following to the beginning of the controller generating that form:

protect_from_forgery :except => [:your_action]

You can also turn off protect_from_forgery for the entire controller by adding the following to the beginning:

skip_before_filter :verify_authenticity_token


It doesn't seem to be a well-solved problem. Point two on this blog post describes how to accomplish the task by using jQuery, but that introduces a Javascript dependency. Weigh your options, I suppose.


You could render a custom tag in the cached markup and replace it with the form rendered on every request.

module CacheHelper  # Our FORM is deeply nested in the CACHED_PARTIAl, which we  # cache. It must be rendered on every request because of its  # authenticity_token by protect_from_forgery. Instead of splitting up the  # cache in multiple fragments, we replace a special tag with the custom  # form.  def cache_with_bla_form(resource, &block)    form = nil    doc = Nokogiri::HTML::DocumentFragment.parse( capture { cache("your_cache_key",&block) } )    doc.css('uncachable_form').each do |element|      form ||= render(:partial => 'uncachable_form', :resource => resource)      element.replace form    end    doc.to_html  endend

And in your view, you just render an empty uncachable_form tag.

<%- cache_with_bla_form resource do %>  # cachable stuff..  <uncachable_form />  # more cachable stuff<%- end %>

Yes, this can be considered as a Hack, but it won't loosen forgery protection, needs no JS, and decrease the performance gain from caching just a bit. I think someone implemented a similar pattern as a Rack Middleware.