【问题标题】:"Can't mass-assign protected attributes" with nested attributes带有嵌套属性的“无法批量分配受保护的属性”
【发布时间】:2012-07-10 00:23:49
【问题描述】:

我已经看到了与此问题相关的其他问题,但到目前为止,答案对我没有用。我正在尝试创建一个注册用户并同时创建组织的表单。用户和组织通过分配表关联。

这是我的表格:

= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|

  = devise_error_messages!

  = f.fields_for :organizations do |f|

    = f.label :name
    = f.text_field :name

  = f.label :email
  = f.email_field :email

  = f.label :password
  = f.password_field :password

  = f.label :password_confirmation
  = f.password_field :password_confirmation

我的注册控制器:

class Users::RegistrationsController < Devise::RegistrationsController
  def new
    @user = User.new
    @user.organizations.build
  end

  def create
    super
  end

  def update
    super
  end
end

我的组织模型:

class Organization < ActiveRecord::Base
  has_many :organization_assignments
  has_many :users, :through => :organization_assignments

  attr_accessible :name
end

和我的用户模型:

class User < ActiveRecord::Base

  has_many :organization_assignments
  has_many :organizations, :through => :organization_assignments

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  accepts_nested_attributes_for :organizations

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :organization_attributes
  # attr_accessible :title, :body

end

我得到的确切错误是:

无法批量分配受保护的属性:organizations_attributes

【问题讨论】:

  • 谢谢,我遇到了同样的问题

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 devise


【解决方案1】:

您必须在User 模型中将:organizations_attributes 添加到attr_accessible

【讨论】:

  • 这与他在用户模型中已有的区别是复数:organizations_attributes 而不是单数:organization_attributes?我收到相同的错误消息,但这并没有解决它。
  • 他的accepts_nested_attributes_for :organizations 模型中有User。取那个符号并附加_attributes,你会得到:organizations_attributes
  • 我很高兴回答您的问题,但是您对 OP 的问题和我的回答缺乏理解并不是拒绝我的理由。来自 the down-vote privilege page:“每当您遇到一个极其草率、不费吹灰之力的帖子,或者一个明显不正确且可能非常不正确的答案时,请使用您的反对票。”。我的回答与此相反;正确、清晰、简洁。
  • 我明白你在说什么,但不同意你的观点,并用我微薄的代表点投票。我发现它是一行“不费吹灰之力的帖子”。如果您要澄清与他的问题的答案相关的非常少的内容(例如,“将行A 替换为B”)清楚而简洁地显示它适合的位置,这将是一个更完整的答案。您的回答说他的问题的解决方案是“attr_accessible :email, :password, :password_confirmation, :remember_me, :organization_attributes :organizations_attributes: 最后一个是双倍和复数的。这是真的吗?
  • 考虑到这正是我所做的(告诉 OP 要更改的内容和位置),我放弃了; 没有2分我也能活。祝您好运解决您的问题。
猜你喜欢
  • 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
相关资源
最近更新 更多