Strong parameters for nested attributes returns “unpermitted parameters” when empty array

瘦欲@ 提交于 2019-11-28 03:14:54

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/17515672/strong-parameters-for-nested-attributes-returns-unpermitted-parameters-when-em

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