简体   繁体   中英

ActionController::InvalidAuthenticityToken Error in controller

So I've started getting this error after I tried to implement AJAX comments in my rails app:

ActionController::InvalidAuthenticityToken in CommentsController#create    

ActionController::InvalidAuthenticityToken

    def handle_unverified_request
      raise ActionController::InvalidAuthenticityToken
    end
  end
end

Here are all the codes from the relevant files:

comments_controller.rb

class CommentsController < ApplicationController


  before_action :find_post

  def create  
    @comment = @post.comments.build(comment_params)
    @comment.user_id = current_user.id

    if @comment.save
      respond_to do |format|
        format.html { redirect_to root_path }
        format.js
      end
    else
      flash[:alert] = "Check the comment form, something went horribly wrong."
      render root_path
    end
  end

Add comments form:

= form_for([post, post.comments.build], remote: true) do |f|
  = f.text_field :content, placeholder: 'Add a comment...', class: "comment_content", id: "comment_content_#{post.id}"

views/comments/create.js.erb

$('#comments_<%= @post.id %>').append("<%=j render 'comments/comment', post: @post, comment: @comment %>");
$('#comment_content_<%= @post.id %>').val('')

comment.rb

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

I have no idea what's causing this error as it worked fine before the introduction of AJAX. I looked up answers to similar problems on stackoverflow and added protect_from_forgery at the top of comments_controller.rb to no avail. I don't get the InvalidAuthenticityToken error alright, but instead, it gives me a different error:

NoMethodError in CommentsController#create

undefined method `id' for nil:NilClass

def create  
  @comment = @post.comments.build(comment_params)
  @comment.user_id = current_user.id #highlighted line

  if @comment.save
    respond_to do |format|

You have to send an authenticity token with your forms, it should be generated in your form_for, so I guess your ajax is just not sending it.

In case it's not automatically generated, you can do it manually: <%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Unless config.action_view.embed_authenticity_token_in_remote_forms is set to true (the default is false), Rails won't generate the hidden input containing the csrf token if the form is a remote one.

This is because ajax powered forms have another mechanism for getting the token & this change means you can now fragment cache html containing this form because it no longer contains content that changes for every user.

This mechanism is adding the csrf tag to the page's meta tags, which the rails javascript can read and add to the ajax request. There is a helper, csrf_meta_tags that does this for you - just add a call to it in the <head> of the html you are rendering (this will usually be in your layout file).

Solution to my problem was to put on first line inside controller:

skip_before_action :verify_authenticity_token, :only => [:create,:inquire_enterprise]

As you can see I am escaping 2 actions which produced the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM