的ActionController :: InvalidAuthenticityToken错误于是我开始收到此错误后,我试图实现我的Rails应用AJAX评论:在控制器
ActionController::InvalidAuthenticityToken in CommentsController#create
ActionController::InvalidAuthenticityToken
def handle_unverified_request
raise ActionController::InvalidAuthenticityToken
end
end
end
这里会显示所有相关的文件代码:
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
添加注释形式:
= 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}"
组
的意见/评论/ 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
我不知道,因为它引入AJAX的前工作正常是什么导致了这个错误。我查找了对stackoverflow类似问题的答案,并在comments_controller.rb
的顶部添加protect_from_forgery
无济于事。我没有得到InvalidAuthenticityToken
错误好吧,而是它给了我一个不同的错误:
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|
你的布局中是否有csrf_meta_tags? –
@FrederickCheung是的,对'csrf_meta_tags'的调用是在布局文件 – Arif