我昨晚开始玩 Rails 4。我正在制作一个简单的博客类型应用程序来熟悉一些更改。我有使用默认脚手架的帖子。
我决定在不使用脚手架的情况下添加评论,当我尝试保存帖子的评论时,我收到此错误:
ActiveModel::ForbiddenAttributesError in CommentsController#create
请求参数ON错误页面:
{"utf8"=>"✓",
"authenticity_token"=>"jkald9....",
"comment"=>{"commenter"=>"Sam",
"body"=>"I love this post!"},
"commit"=>"Create Comment",
"post_id"=>"1"}
这是评论 Controller 的创建操作:
class CommentsController < ApplicationController
def create
@post = post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body, :post_id)
end
end
这是我的评论的非常基本的迁移。
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :post, index: true
t.timestamps
end
end
end
我对强类型参数做错了什么?或者也许 Rails 4 中还有其他我遗漏的更改?
最佳答案
有点疏忽,但我想我会回答这个问题,以防其他人正在致力于将类似的 Rails 3 代码移植到 Rails 4。
您需要将 comment_params 传递到批量分配中,如下所示:
@comment = @post.comments.create(comment_params)
关于ruby-on-rails - 在 Rails 4 中向模型和强参数添加注释会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17179553/