Nested form - cannot assign a protected attribute

I am a little puzzled by this because I feel like I avoided common errors (e.g. with the attr_accessible error or leaving it completely ), but I still get

Can't mass-assign protected attributes: home, work 

the mistake is here. I suppose I'm missing something, but I'm not sure what.

In any case, in my new application, users have one homework and one work (each of which belongs to the user), and I want users to enter them during registration. So, in my models:

user.rb

 attr_accessible :email, :first_name, :last_name, :password, :password_confirmation, :home_attributes, :work_attributes has_one :home, :work accepts_nested_attributes_for :work, :home has_secure_password 

home.rb

 attr_accessible :address, :latitude, :longitude, :user_id belongs_to :user validates :address, presence: true 

work.rb

 attr_accessible :address, :latitude, :longitude, :user_id belongs_to :user validates :address, presence: true 

in my controller

users_controller.rb

 def new @user = User.new respond_to do |format| format.html # new.html.erb format.json { redirect_to @user } end end 

and in my form:

views / users / _form.html.haml

 = form_for @user do |f| - if @user.errors.any? .error_explanation %h2 = pluralize(@user.errors.count, "error") prohibited this post from being saved: %ul - @user.errors.full_messages.each do |msg| %li= msg = f.label :first_name = f.text_field :first_name = f.label :last_name = f.text_field :last_name = f.label :email = f.text_field :email = f.label :password = f.password_field :password = f.label :password_confirmation, "Re-Enter Password" = f.password_field :password_confirmation = f.fields_for :home do |builder| = builder.label :address, "Home address" = builder.text_field :address %br = f.fields_for :work do |builder| = builder.label :address, "Work address" = builder.text_field :address .btn-group = f.submit 'Sign Up!', class: "btn" 
+4
source share
1 answer

It looks like you have not configured your instance variable to include these attributes.

In your controller you should have something like this

 def new @user = User.new @user.homes.build @user.works.build respond_to do |format| format.html # new.html.erb format.json { redirect_to @user } end end 

If you do not create these attributes, the form does not know what to do.

Change Fixed syntax for building a nested resource

+3
source

All Articles