簡體   English   中英

strong_params:處理嵌套對象/屬性的動態數量

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

問題

我有一個模型Foo,它可以接受模型欄的嵌套屬性。 對表單中的嵌套模型使用rails約定, form_forfields_for創建表單的params哈希:

{...
  :foo => {
    :name => "Lunes",
    :bar_attributes => {
      1 => {
         label: "gato"
         },
      2 => {
         label: "perro"
         }
    }
  }
}

但是,strong_params希望我將每個屬性明確列入白名單。

def foo_params
  params.require(:foo).permit(:name, bar_attributes: {1: [:label], 2: [:label]}
end

問題:

:bar_attributes的哈希數是動態的。 我是否需要動態生成foo_params方法,特別是: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