Broken AJAX requests after updating to Rails 2.3.15
Published on: 15 Jan 2013
After updating Rails to 2.3.15 in a Rails 2.3 app, I found that some AJAX requests were suddenly not only not working properly, but they also were a bit tricky to debug, as they error caused the logged user to be kicked out the app.
The strangest thing was the server log claiming that my current_user
was not present after the AJAX call. I needed the current_user to get to get to do the request, so it WAS there in the beginning, but in the response, the current_user
ceased to exist, so… what was happening?
Well, it turned out to be that Devise (a way old version of the gem, by the way) was kicking the user out due to the impossibility of checking the CSRF token properly, because it was not being encoded and sent in the AJAX request in the first place.
Solving this is easy, and it is something that should have been done from the start. Working with ‘inherited’ legacy apps sometimes brings this sort of problems in the long run.
- Add the
csrf_meta_tag
line in theheader
section of your applicationlayout
. - Modify your javascript AJAX requests so they send the AUTH_TOKEN encoded along with the rest of the data.
Here are some StackOverflow questions that helped me figure out what was happening and how to solve it: one, two, and three.