[英]strong_params: Handling Dynamic Number of Nested Objects/Attributes
I have a model Foo that can accept nested attributes for a model Bar. 我有一个模型Foo,它可以接受模型栏的嵌套属性。 Using rails conventions for nested models in forms,
form_for
and fields_for
create a params
hash of the form: 对表单中的嵌套模型使用rails约定,
form_for
和fields_for
创建表单的params
哈希:
{...
:foo => {
:name => "Lunes",
:bar_attributes => {
1 => {
label: "gato"
},
2 => {
label: "perro"
}
}
}
}
But, strong_params wants me to explicitly whitelist each attribute. 但是,strong_params希望我将每个属性明确列入白名单。
def foo_params
params.require(:foo).permit(:name, bar_attributes: {1: [:label], 2: [:label]}
end
The number of hashes in :bar_attributes
is dynamic. :bar_attributes
的哈希数是动态的。 Do I need to dynamically generate my foo_params
method, specifically the :bar_attributes
hash? 我是否需要动态生成
foo_params
方法,特别是:bar_attributes
哈希? Or is there a way to whitelist the params that I want generally, and not for each individual sub-hash of :bar_attributes
. 还是有一种方法可以将我通常想要的参数列入白名单,而不是对
:bar_attributes
每个子哈希进行白名单:bar_attributes
。
使用params.require(:foo).permit(:name, bar_attributes: [:label]}
应该可以正常工作,但bar_attributes
是bar_attributes
键是字符串(即“ 1”和“ 2”而不是1和2)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.