gpt4 book ai didi

ruby-on-rails - ActionController::InvalidAuthenticityToken Controller 错误

转载 作者:行者123 更新时间:2023-12-05 01:46:03 26 4
gpt4 key购买 nike

因此,在我尝试在我的 Rails 应用程序中实现 AJAX 评论后,我开始收到此错误:

ActionController::InvalidAuthenticityToken in CommentsController#create    

ActionController::InvalidAuthenticityToken

def handle_unverified_request
raise ActionController::InvalidAuthenticityToken
end
end
end

以下是相关文件中的所有代码:

评论 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}"

views/comments/create.js.erb

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

评论.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|

最佳答案

我的问题的解决方案是在 Controller 内的第一行:

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

如您所见,我正在转义 2 个产生错误的操作。

关于ruby-on-rails - ActionController::InvalidAuthenticityToken Controller 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37945850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com