2016-06-21 63 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