Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails form page caching including authenticity_token

I have a simple Ruby on Rails form which includes an authenticity_token. Unfortunatly, I missed that when you page cache this page then the Authenticity Token becomes invalid. I'm glad I figured it out however.

How do you solve caching in such a case?

like image 454
jacob Avatar asked Mar 05 '10 04:03

jacob


2 Answers

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.

like image 38
Matchu Avatar answered Oct 20 '22 15:10

Matchu


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
like image 69
Mike Trpcic Avatar answered Oct 20 '22 16:10

Mike Trpcic