Question

I am in the process of upgrading my app from Rails 2.3 to Rails 3. I read that I need to insert

<%= csrf_meta_tag %>

in my layouts, which I did. Unfortunately, when I used ajax requests, I kept being logged out. After a little research, I found an older way was to add

$j(document).ajaxSend(function(e, xhr, options) {
  var token =$j("meta[name='csrf-token']").attr("content");
  xhr.setRequestHeader("X-CSRF-Token", token);  
});

in my application.js file. It now works properly (It seems I actually don't need the csrf_meta_tag).

Is it normal I had to add these 4 lines of code in my application.js instead of just the csrf_meta_tag, or am I just missing something?

Was it helpful?

Solution

Firstly, you do need csrf_meta_tag. If you don't use it in your layout the csrf-token meta will not be generated then your application.js fix stops working.

The jquery-ujs gem (jquery-rails) should take care of this for you. It's possible the version you use have some bug. (I do remember there's a related bug in 3.0.x, but couldn't recall the exact issue). Try updating jquery-ujs and re-generate jquery (rails generate jquery:install), remove rails.js to see if the issue be fixed.

Bonus note: as of rails 3.1, csrf_meta_tag has been renamed to csrf_meta_tags, but the former one could still be used.

Please see jquery-ujs on github.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top