【发布时间】:2013-05-08 08:27:10
【问题描述】:
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
在控制器中。我的其他(非多态)模型没有这样的问题,这就是为什么我怀疑它与多态性有关。有任何想法吗?
【问题讨论】:
-
实际上,这似乎是由 CanCan 引起的错误,我用它来进行基于角色的授权 - 禁用它可以创建 cmets。嗯。
标签: parameters ruby-on-rails-4 cancan mass-assignment polymorphism