10
votes

I have a controller which uses AJAX for CRUD, however whenever I click on one of my remote links (Delete for example) I see the rails server has decided to log me out and redirect me. Inspection of the server logs state that it cannot verify CSRF Authenticity. How do I include the CSRF token in my request?

Running: - Rails 3.1 - Devise 1.4.4 - jquery-rails 1.0.13

Relevant Controller Action:

 def destroy
     @article = Article.find(params[:id])
      if @article.destroy
        flash[:notice] = "Article deleted."
        respond_to do |format|
        format.html{redirect_to articles_path}
        format.js{}
      end
      else
        flash[:error] = "Try Again."
        redirect_to :back
      end

Layouts/application.html.erb

      <head>
    <title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap-1.1.1.min.css>
    <%= stylesheet_link_tag "application" %>
    <%= javascript_include_tag :defaults %>
   <script type="text/javascript">jQuery.ajaxSetup({ beforeSend: function (xhr) { xhr.setRequestHeader("Accept", "text/javascript"); } });</script>
    <%= csrf_meta_tag %>
    <%= yield(:head) %>
  </head>

Thanks in advance.

2

2 Answers

8
votes

Rails 3.1 uses the gem 'jquery-rails', which wants you to have this in your application.js file:

//= require jquery
//= require jquery_ujs

I had forgotten the jquery_ujs and was getting the same problem as you.

4
votes

You should have this in your html page:

<%= csrf_meta_tag %>

which generates the following:

<meta name="csrf-param" content="authenticity_token"/>
<meta name="csrf-token" content="the token comes here"/>

Whenever you do POST (DELETE, PUT are actually POST but with _method set dependently), you should get include the {authenticity_token: "the token comes here"} in the data your post together with.