“Can't mass-assign protected attributes” with nested attributes

爷,独闯天下 提交于 2019-12-10 09:25:16

问题


I've seen other questions with this problem, but so far the answers haven't worked for me. I'm trying to have a form that registers a User, and creates an Organization at the same time. The User and Organization are associated via an assignment table.

Here is my form:

= 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

My Registration controller:

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

  def create
    super
  end

  def update
    super
  end
end

My Organization model:

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

  attr_accessible :name
end

and my User model:

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

The exact error I'm getting is:

Can't mass-assign protected attributes: organizations_attributes


回答1:


You have to add :organizations_attributes to attr_accessible in the User model.



来源:https://stackoverflow.com/questions/11405065/cant-mass-assign-protected-attributes-with-nested-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!