Ruby on rails 4 具有多个嵌套属性的模型的强参数
我如何为如下参数使用强参数:Ruby on rails 4 具有多个嵌套属性的模型的强参数,ruby-on-rails-4,nested-attributes,has-many,strong-parameters,Ruby On Rails 4,Nested Attributes,Has Many,Strong Parameters,我如何为如下参数使用强参数: { ... attributes of a model, related_model_attributes => [ RANDOM_HASH_KEY => { attr_1 => value_1, ... other attributes }, ANOTHER_RANDOM_KEY => { attr_1 => value_1, ... other attributes} ...
{
... attributes of a model,
related_model_attributes => [
RANDOM_HASH_KEY => { attr_1 => value_1, ... other attributes },
ANOTHER_RANDOM_KEY => { attr_1 => value_1, ... other attributes}
...
]
}
{ thing: {
thangs_attributes: {
'some_synethic_index' => {
attribute: value
},
'some_other_index' => {
attribute: value
}
}
}
如果我使用正常的许可样式,如ff代码段:
permit!(... model attributes, related_model_attributes: [{:attr_1, ..other attributes]])
它会在随机哈希键上抛出不允许的错误
如何将强参数与has\u many一起使用?除了明显的、丑陋的方法外,没有官方认可的方法 给定如下哈希:
{
... attributes of a model,
related_model_attributes => [
RANDOM_HASH_KEY => { attr_1 => value_1, ... other attributes },
ANOTHER_RANDOM_KEY => { attr_1 => value_1, ... other attributes}
...
]
}
{ thing: {
thangs_attributes: {
'some_synethic_index' => {
attribute: value
},
'some_other_index' => {
attribute: value
}
}
}
其基本思想是允许基于外观的thang_属性
散列中的键
像这样的
def thing_params
thangs_attributes = params[:thing][:thangs_attributes].keys.each_with_object([]) do |k, memo|
memo << { k => [:id, '_destroy', :attribute] }
end
params.require(:thing).permit(thangs_attributes: thangs_attributes)
end
def thing_参数
thangs_attributes=params[:thing][:thangs_attributes]。键。每个带有对象([])的_都做| k,memo|
备注[:id,'.'u destroy',:attribute]}
结束
参数require(:thing).permit(thangs_属性:thangs_属性)
结束
它应该为
thangs\u attributes
中的每个随机索引键设置嵌套哈希。或者,也可以不安全地调用params.require(:thing).permit代码>允许任何和所有参数。是-此方法有效-尽管我最近一直在使用JSON模式以获得更健壮的解决方案。