Rails - How to add CSRF Protection to forms created in javascript?

I'm using backbone.js and it works great. but the forms I'm creating as a javascript template lacks the rails csrf protection token. How do I add it to templates I'm creating in javascript?


Best way I solved this, inside the form:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Update:

It looks like the form_authenticity_token is private for controllers in the newer rails versions.

If that's the case for you, what I suggest is: declare a variable in a controller like: @form_token = form_authenticity_token and use it in the view you are looking for.


If you have <%= csrf_meta_tag %> in your layout somewhere and that is accessible to you from the js, then you can access it using $('meta[name="csrf-token"]')

See http://eunikorn.blogspot.com/2011/07/working-with-backbonejs-in-harmony-with.html for an idea on how to hack in csrf support into each backbone request


You can prepend the csrf token to every form that uses 'post' or 'delete'. Here it is in coffeescript:

$ -> 
  for f in $("form")
    if f.method == 'post' or f.method == 'delete'
      $(f).prepend("<input type='hidden' name='authenticity_token' value='" + token + "'>")

Make sure you have <%= csrf_meta_tags %> in your layout. It should already be in the standard 'application' layout, but add it if you're using a different layout.