at.
at.

Reputation: 52540

accepts_nested_attributes_for not working as expected for User model in Rails

I'm getting the following error when trying to submit a nested attribute:

Can't mass-assign protected attributes: staff

My User model (created by Devise):

class User < ActiveRecord::Base
  attr_accessible :name
  has_one :staff
  accepts_nested_attributes_for :staff, reject_if: :new_record?
end

My Devise registrations/edit.html.erb view:

<%= f.fields_for resource.staff do |s| %>
  <%= s.label :notification_email %>
  <%= s.email_field :notification_email, placeholder: 'Enter notification email' %>
<% end %>

What gets submitted in the HTML post as a parameter:

"user"=>{"name"=>"Scott",
"staff"=>{"notification_email"=>"[email protected]"}}

I expected the HTML post parameter for staff to be "staff_attributes" rather than just "staff" based on the documentation for nested attributes.

Did I do something wrong? Do I really need to add staff to the attr_accessible list of attributes? Does this not work with Devise? I did have to use resource instead of @user in the view.

Upvotes: 1

Views: 697

Answers (2)

nickcen
nickcen

Reputation: 1692

  1. Pass in the symbol instead of an instance.

  2. add attr_accessible :staff_attributes in the user model.

  3. initialize the staff instance inside user controller's new method.

Upvotes: 0

Zakwan
Zakwan

Reputation: 1072

in your view, remove resource. as following:

<%= f.fields_for :staff do |s| %>

in the model, add :staff_attribute (or staff_attributes not sure) to attr_accessible

Upvotes: 1

Related Questions