简体   繁体   English

strong_params:处理嵌套对象/属性的动态数量

[英]strong_params: Handling Dynamic Number of Nested Objects/Attributes

The Problem 问题

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_forfields_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 question: 问题:

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_attributesbar_attributes键是字符串(即“ 1”和“ 2”而不是1和2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM