【问题标题】:Rails 4 with CanCan: unknown attribute error after including load_and_authorize_resource带有 CanCan 的 Rails 4:包含 load_and_authorize_resource 后出现未知属性错误
【发布时间】:2013-06-21 18:35:04
【问题描述】:

我在 Rails 4 中工作,并且已经让 CanCan 在 this issue 的指示下正常工作,除了我认为可能相对常见的一个用例。

我有一个Comment 模型,has_many :comments, through: :replies 用于嵌套 cmets。所有这些都运行良好,直到我将 load_and_authorize_resource 添加到我的 cmets 控制器。问题似乎源于向我的创建操作发送可选:parent_comment_id 属性的隐藏字段。

我已通过强参数允许此属性:

def comment_params
  params.require(:comment).permit(:content, :parent_comment_id, :post_id, :comment_id, :user_id)
end

如果包含:parent_comment_id,我可以创建关联:

if comment_params[:parent_comment_id] != nil
  Reply.create({:parent_comment_id => comment_params[:parent_comment_id], :comment_id => @comment.id})
end

但是一旦我添加了load_and_authorize_resource,我就会收到:parent_comment_id 的未知属性错误。我错过了什么?

【问题讨论】:

    标签: cancan ruby-on-rails-4 strong-parameters


    【解决方案1】:

    解决方案在我睡梦中出现。这是我为解决问题所做的:

    comment_params 在创建时通常没有问题的唯一原因是因为我排除了额外的 :parent_comment_id 参数,如下所示:

    @comment = post.comment.create(comment_params.except(:parent_comment_id))
    

    但是,当 CanCan 使用 comment_params 方法时,它没有这样的卫生。因此,问题。在每个控制器的基础上向 CanCan 添加卫生设施会很麻烦,所以我做了我应该做的事情,而不是在:comment 中传递:parent_comment_id,我使用hidden_field_tag 将它传递到外面的:comment 并通过普通的旧params 访问它。

    我希望这对犯类似错误的其他人有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2018-01-16
      相关资源
      最近更新 更多