Rails 4 附带了 strong_parameters,这是一个很好的补充——但我遇到了一个问题。我有一个多态模型Comment
,我无法让控制器接受它需要的参数。这是我的代码(为清楚起见而缩短):
路线:
resources :articles do
resources :comments
end
楷模:
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
控制器:
class CommentsController < ApplicationController
before_action :get_commentable
def create
@comment = @commentable.comments.new(comment_params)
if @comment.save
redirect_to @commentable, :notice => "Thank you!"
else
render :new
end
end
private
def get_commentable
resource, id = request.path.split("/")[1,2]
@commentable = resource.singularize.classify.constantize.find(id)
redirect_to :home unless defined?(@commentable)
end
def comment_params
params.require(:comment).permit(:title, :message)
end
end
发布的参数(来自文章#show 上的表格):
{"authenticity_token"=>"v70nN8aFpofNw9vbVjhpsm9SwLOwKlOpNOEOTozUwCk=",
"comment"=>{"title"=>"Test","message"=>"Testing"},
"article_id"=>"1"}
在我看来它应该可以工作,但无论我尝试什么,我都会得到ActiveModel::ForbiddenAttributesError in CommentsController#create
- 即使我尝试了
def comment_params
params.permit!
end
在控制器中。我的其他(非多态)模型没有这样的问题,这就是为什么我怀疑它与多态性有关。有任何想法吗?