新更新
移动参数允许从模型到控制器的责任,并使用comment_attributes 而不是@vinodadhikary 指出的评论
使用 better_errors REPL,我将问题追溯到sanitize_for_mass_assignment
方法。当attributes.permitted?
它返回时false
。但是这样做attributes.permit(:article_id, :name, :email, :body)
会完全返回我的输入参数!:
>> attributes
=> {"name"=>"Commenter", "email"=>"commenter@mail.com", "body"=>"Here is the comment >> body!! :D"}
>> attributes.permit(:article_id, :name, :email, :body)
=> {"name"=>"Commenter", "email"=>"commenter@mail.com", "body"=>"Here is the comment body!! :D"}
>> attributes.permitted?
=> false
上下文和代码
在尝试接触 Rails 4 时,我遇到了(我认为)强参数使用的问题。
我有一个可以有很多评论的文章类。创建新评论时:
@comment = @article.comments.build(params[:comment])
我收到以下错误(指向此行):
/articles/1/comments 处的 ActiveModel::ForbiddenAttributesError
型号如下:
class Article < ActiveRecord::Base
validates_presence_of :title, :content
validates_uniqueness_of :title
has_many :comments, :dependent => :destroy
accepts_nested_attributes_for :comments
end
注释:
class Comment < ActiveRecord::Base
belongs_to :article
validates_presence_of :article_id, :author, :body, :content
end
文章控制器在私人部分有这个:
def article_params
params.require(:article).permit(:title, :content, comments_attributes: [:article_id, :name, :email, :body])
end
评论控制器代码是:
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.build(params[:comment]) # <--- It fails here
respond_to do |format|
if @comment.save
format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
format.json { render action: 'show', status: :created, location: @comment }
else
format.html { render action: 'new' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end