Search code examples
ruby-on-railsdeviseruby-on-rails-3.1csrf

Devise Logging User out on AJAX request. Rails 3.1


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.


Solution

  • 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.