Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby on rails 4 - Strong parameters for nested attributes returns "unpermitted parameters" when empty array

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...