的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