9

Assuming a User model using Rails4 with strong_parameters.

class User < ActiveRecord::Base
  has_secure_password

 accepts_nested_attributes_for :identity

//  rest of code omitted for brevity
end

If I refer to the guide I should be able to do

def user_params
    params.require(:user).permit(:email, identity_attributes: [])
end

to allow mass_assignment of each identity_attributes whatever their names or number. But this run in a "Unpermitted parameters: identity_attributes"

But if I specify the identity_attributes it works

def user_params
    params.require(:user).permit(:email, identity_attributes: [:last_name, :first_name])
end

I have many attributes in Identity, I would be able to mass_assign them through User without specifying all of them.

Am I missing something ? Is it a bug ?

Cheers

souravlahoti
  • 716
  • 2
  • 8
  • 29
phron
  • 1,795
  • 17
  • 23

1 Answers1

21

You have to specify the identity's attributes you want to updated, including the :id of the identity entity.

you will have something like that :

def user_params 
  params.require(:user).permit(:email, identity_attributes: [:id, :last_name, :first_name]) 
end

if you don't specify the :id, Rails will try to create an entity instead of updating it. I spend all the week-end struggling on a simple one-to-many relationship using accepts_nested_attributes_for because I didn't specified the id in the permitted attributes.

d34n5
  • 1,308
  • 10
  • 18
  • Thanks it's right when you have a one-to-many relationship (and it seems logical to specify which object in the 'many part' should be updated) but it seems not to be the case with a 1-to-1 relationship (It works fine without specifying the identity.id). The question was about the example provided in docs where the nested attributes are an empty array ^_^ (and that's does not work as far as I can see) – phron Jul 10 '13 at 07:08
  • OOps re-try this morning, you are right even for a 1-to-1 relationship... If nested object id not provided it seems to delete the original record and recreate a new one instead of updating the existing one (!!). The docs are not very clear when strong_parameters and nested_attributes !!! Ĥave swing Cheers – phron Jul 10 '13 at 07:49
  • @d34n5 you're the great :). But I was wondering why mongoid missed this important thing in their documentation. – Taimoor Changaiz Apr 23 '14 at 09:18