Trying to use nested attributes to create an Organization
and a User
in one form. I'm getting the following error: Can't mass-assign protected attributes: user (ActiveModel::MassAssignmentSecurity::Error)
Pulling my hair out on this one
organization.rb
class Organization < ActiveRecord::Base
attr_accessible :name, :users_attributes
has_many :users, dependent: :destroy
accepts_nested_attributes_for :users
end
user.rb (using devise)
class User < ActiveRecord::Base
attr_accessible :email
belongs_to :organization
end
new.html.haml
= form_for @organization do |f|
= f.label :name, "Company Name"
= f.text_field :name, placeholder: "Company Name"
= f.fields_for :user do |ff| -# tried :users here and the form doesn't render
= ff.label :email, "Email Address"
= ff.email_field :email, placeholder: "Email Address"
= f.submit "Create Account"
This has been answered a lot on Stackoverflow.
f.fields_for :users
And in the controller, you need to build a user:
@organization.users.build
You get Can't mass-assign protected attributes: user
because the user attribute is not accessible, because it doesn't exist.