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发布的参数(来自articles#show上的表单):
{"authenticity_token"=>"v70nN8aFpofNw9vbVjhpsm9SwLOwKlOpNOEOTozUwCk=",
"comment"=>{"title"=>"Test","message"=>"Testing"},
"article_id"=>"1"}在我看来,它应该可以工作,但无论我尝试什么,我都会得到ActiveModel::ForbiddenAttributesError in CommentsController#create -即使我尝试了也是如此
def comment_params
params.permit!
end在控制器中。我的其他(非多态)模型没有这样的问题,这就是为什么我怀疑它与多态有关。有什么想法吗?
发布于 2013-05-15 13:00:59
因为缺乏答案似乎表明我在这里找错了人。问题不在于strong_parameters,而在于我用来进行基于角色和操作的授权的CanCan gem。显然,这与CanCan如何将参数赋值给对象有关(CanCan接管了默认的ActionController方法)-请参阅this bug report中的详细信息,特别是the reply from "rewritten"。简而言之,把它放到我的应用程序控制器中就解决了这个问题:
before_filter do
resource = controller_name.singularize.to_sym
method = "#{resource}_params"
params[resource] &&= send(method) if respond_to?(method, true)
end更新:
正如@scaryguy所指出的,如果上面的方法是从一个没有关联模型的控制器中调用的,那么它就会崩溃。解决方案是简单地命名方法并将其作为before_filter调用,同时显式地将其排除在那些没有模型的控制器中(因此无论如何都不会从CanCan的自动能力分配中受益)。我估计是这样的:
before_filter :can_can_can
def can_can_can
resource = controller_name.singularize.to_sym
method = "#{resource}_params"
params[resource] &&= send(method) if respond_to?(method, true)
end然后在无模型控制器中:
skip_before_filter :can_can_canhttps://stackoverflow.com/questions/16435930
复制相似问题