2014-02-11 80 views
0

當使用form_for([@ post,@comment])發送一個post請求到我的評論控制器時,我收到一個錯誤。創建評論。強烈的參數和嵌套的參數 - Rails 4

::加載ActiveModel在ForbiddenAttributesError#CommentsController創建

線會導致錯誤:

@comment = @post.comments.build(params[:comment]) 

我知道它已經降到了一個強大的參數問題,但我似乎無法得到它的權利。目前,我上崗模式是:

posts.rb

class Post < ActiveRecord::Base 
    has_many :comments, dependent: :destroy 
end 

並徵求意見:

comment.rb

class Comment < ActiveRecord::Base 
    belongs_to :post 
end 

我目前強勁的參數設置進行了點評控制器是:

comments_controller.rb

private 

    def comment_params 
     params.require(:post).permit(comment: [:name, :body]) 
    end 

最後參數,該錯誤消息被報道是:

{"utf8"=>"✓", 
"authenticity_token"=>"MSX1PrrvfzYBr/DNYaMgSw3opWmaJs82xd11JfLPIqI=", 
"comment"=>{"name"=>"", 
"body"=>""}, 
"commit"=>"Create Comment", 
"post_id"=>"1"} 

任何人有在我的強烈PARAMS設置被破壞任何想法 - 任何想法將不勝感激。謝謝!

回答

2

在你的控制器中你需要你的文章,而不是你的評論。也許嘗試:

def comment_params 
    params.require(:comment).permit(:name, :body) 
end 

然後執行:

@comment = @post.comments.build(comment_params) 

看看是否有幫助。

+0

謝謝您的回答它的讚賞。有沒有任何指南或文檔,你會推薦我閱讀嵌套參數? – Tom

+0

當然,請查看這裏的github頁面:https://github.com/rails/strong_parameters。 – jklina

1

幾個問題...

的一個問題是,你是不是在build方法使用comment_params ...

@comment = @post.comments.build(params[:comment]) 

應該

@comment = @post.comments.build(comment_params[:comment]) 

但我們有另一個問題,你的params實際上不是{post: {comment: 'stuff here'}}像你的comment_params方法所示。它實際上{comment: 'stuff here'}

所以,你應該改變評論PARAMS:

def comment_params 
    params.require(:comment).permit(:name, :body) 
end 

然後建立您的評論:

@comment = @post.comments.build(comment_params)