2016-06-21 64 views
0

的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| 
+0

你的布局中是否有csrf_meta_tags? –

+0

@FrederickCheung是的,对'csrf_meta_tags'的调用是在布局文件 – Arif

回答

0

,你必须在你的表单发送真实性令牌,应该在你的form_for生成的,所以我想你阿贾克斯只是没有发送它。

在情况下,它不会自动生成,你可以做手工:<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

+0

那里,我应该把这条线放在哪里? – Arif

0

除非config.action_view.embed_authenticity_token_in_remote_forms设置为true(默认为false),Rails会不会产生含有CSRF令牌,如果表单的隐藏输入是一个遥远的。

这是因为ajax动力表单有另一种获取令牌的机制&这种改变意味着您现在可以对包含此表单的缓存html进行分段处理,因为它不再包含每个用户都会更改的内容。

这种机制被添加CSRF标记的网页的meta标签,它的JavaScript可以读取并添加到Ajax请求的轨道。有一个助手,csrf_meta_tags为你做这个 - 只需要在你正在渲染的html的<head>中添加一个调用(这通常会在你的布局文件中)。

+0

显然,我已经在布局文件中有'csrf_meta_tags'(我之前一定忽略了它)。我在表单中添加了':authenticity_token => true',并清除了错误。但现在,问题是我每次添加注释时都会重新加载整个页面,就像之前的情况一样ajax – Arif

+0

是否发生了ajax请求?听起来像你可能没有轨道javascript加载 –

+0

ajax正在工作之前,它突然开始抛出真实性的错误,所以我猜JavaScript的加载。如果不是,我怎么确定它是?这里是表单现在的样子:'= form_for([post,post.comments.build],:authenticity_token => true,remote:true)do | f |' – Arif