首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 4中多态模型的ForbiddenAttributesError

Rails 4中多态模型的ForbiddenAttributesError
EN

Stack Overflow用户
提问于 2013-05-08 16:27:10
回答 1查看 1.2K关注 0票数 1

Rails 4附带了strong_parameters,这是一个很好的补充--但我在使用它时遇到了问题。我有一个多态模型Comment,我无法让控制器接受它所需要的参数。以下是我的代码(为清晰起见,请缩短):

路由:

代码语言:javascript
复制
resources :articles do
  resources :comments
end

型号:

代码语言:javascript
复制
class Article < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

控制器:

代码语言:javascript
复制
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上的表单):

代码语言:javascript
复制
{"authenticity_token"=>"v70nN8aFpofNw9vbVjhpsm9SwLOwKlOpNOEOTozUwCk=",
"comment"=>{"title"=>"Test","message"=>"Testing"},
"article_id"=>"1"}

在我看来,它应该可以工作,但无论我尝试什么,我都会得到ActiveModel::ForbiddenAttributesError in CommentsController#create -即使我尝试了也是如此

代码语言:javascript
复制
  def comment_params
    params.permit! 
  end

在控制器中。我的其他(非多态)模型没有这样的问题,这就是为什么我怀疑它与多态有关。有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-15 13:00:59

因为缺乏答案似乎表明我在这里找错了人。问题不在于strong_parameters,而在于我用来进行基于角色和操作的授权的CanCan gem。显然,这与CanCan如何将参数赋值给对象有关(CanCan接管了默认的ActionController方法)-请参阅this bug report中的详细信息,特别是the reply from "rewritten"。简而言之,把它放到我的应用程序控制器中就解决了这个问题:

代码语言:javascript
复制
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的自动能力分配中受益)。我估计是这样的:

代码语言:javascript
复制
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

然后在无模型控制器中:

代码语言:javascript
复制
skip_before_filter :can_can_can
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16435930

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档