Rails 3, UJS, and CSRF Meta Tags
ShareThis
February 24th 2010
The past couple of days I have really had a chance to play around with writing new apps in Rails 3 beta. One thing I am really excited about is Unobtrusive Javascript (UJS) support in Rails 3. There is one thing you will need to know to get up and running with UJS in Rails 3.
I was staring for almost an hour at a simple view last night that used the standard,
link_to "delete", model, :confirm => "Are you sure?", :method => :delete
After reading the Rails 3 Javscript event handlers and pulling my hair out searching for if Rails 3 changed anything, the logs were still logging a GET request. I was never seeing the confirm dialog. Well it turns out there is a little something you need added to your layout in the head section:
csrf_meta_tag
csrf_meta_tag is a helper that returns two HTML tags. They include information necessary for Rails' new, beefy XSS support with good old protect_from_fogery. You will need these for Rails' Javascript to work and you will need it for security.
On to UJS in Rails 3. In previous version of Rails I attempted to stay away from the usage of Javascript helpers and things like :method => :delete because my pure JS background made me want to throw up at the sight of those ugly onclick and onsubmit inline event handlers. Rails 3 does away with all this and uses HTML5’s custom data attributes. When you use :method => :delete and :confirm now you will see two new attributes in your links: data-method and data-confirm. Rails 3 uses these custom data attributes to perform the same tasks as before but unobtrusively. This is one of the most important facelifts of ActionPack.
Rails 3 also changes how we use remote form and link helpers. In Rails 2 you would write:
remote_form_for(@post)
in Rails 3:
form_for(@post, :remote => true)
For links we now write
link_to "some action", my_action_path(@post), :remote => true
The above will add data-remote=“true”. If you would like to change the HTTP method performed also pass the :method option. It will use the sam data-method attribute used for delete links.