【问题标题】:Getting "Can't mass-assign protected attributes:" for nested_attributes获取嵌套属性的“无法批量分配受保护的属性:”
【发布时间】:2013-06-06 05:47:31
【问题描述】:

我在 Rails3 上,我有两个模型,User 和 Post。用户将帖子作为嵌套属性。当我尝试保存用户时,我得到 Can't mass-assign protected attributes:.....

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 nested-attributes mass-assignment attr-accessible


    【解决方案1】:

    在你的帖子模型中试试这个attr_accessible

    http://railscasts.com/episodes/26-hackers-love-mass-assignment

    【讨论】:

      【解决方案2】:

      如果模型定义如下:

      用户.rb

      class User < ActiveRecord::Base
        attr_accessible  :name, :posts_attributes
        has_many :posts
        accepts_nested_attributes_for :posts
      end
      

      post.rb

      class Post < ActiveRecord::Base
        attr_accessible :title, :content :user_id
      end
      

      那么一切都会好起来的。您可以将带有帖子的用户保存为嵌套属性。

      这是给初学者的示例代码:)

      https://github.com/railscash/sample_change_user_role

      【讨论】:

        【解决方案3】:

        Mass Assignment 是 Rails 赋予使用参数​​散列构造对象的行为的名称。它是“批量赋值”,因为您通过单个赋值运算符为属性分配多个值。

        下面的sn-ps对Post模型的name和topic属性进行批量赋值:

        Post.new(:name => "John", :topic => "Something")
        Post.create(:name => "John", :topic => "Something")
        Post.update_attributes(:name => "John", :topic => "Something")
        

        为了使其工作,您的模型必须允许对您传入的哈希中的每个属性进行批量分配。

        有两种情况会失败:

        您有一个不包含 :name 的 attr_accessible 声明

        您有一个 attr_protected,其中包含 :name

        最近成为默认设置,必须通过 attr_accessible 手动将属性列入白名单,以便批量分配成功。在此之前,默认情况下属性是可分配的,除非它们被显式列入 attr_protected 的黑名单或任何其他属性被列入 attr_accessible 的白名单。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-09-05
          • 2012-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-04
          • 1970-01-01
          相关资源
          最近更新 更多