嵌套属性的强参数返回“不允许的参数";空数组时 [英] Strong parameters for nested attributes returns "unpermitted parameters" when empty array
问题描述
假设一个用户模型使用带有 strong_parameters 的 Rails4.
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
允许对每个身份属性进行mass_assignment,无论它们的名称或编号如何.但这在不允许的参数:identity_attributes"中运行
to allow mass_assignment of each identity_attributes whatever their names or number. But this run in a "Unpermitted parameters: identity_attributes"
但是如果我指定了 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
Identity 中有很多属性,我可以通过 User 批量分配它们,而无需指定所有属性.
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 ?
干杯
推荐答案
您必须指定要更新的身份属性,包括身份实体的 :id.
You have to specify the identity's attributes you want to updated, including the :id of the identity entity.
你会有类似的东西:
def user_params
params.require(:user).permit(:email, identity_attributes: [:id, :last_name, :first_name])
end
如果你没有指定:id,Rails 将尝试创建一个实体而不是更新它.我整个周末都在使用 accepts_nested_attributes_for 在一个简单的一对多关系上挣扎,因为我没有在允许的属性中指定 id.
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.
这篇关于嵌套属性的强参数返回“不允许的参数";空数组时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!