1

如何使用強大的參數PARAMS這樣的:強大的參數屬性

{ 
    ... 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} 
     ... 
    ] 
} 

如果我使用普通許可證的風格像FF片段:

permit!(... model attributes, related_model_attributes: [{:attr_1, ..other attributes]]) 

它會在隨機哈希鍵上拋出和不允許的錯誤。

我如何與has_many一起使用強參數?

回答

1

除了明顯的醜陋之外,沒有官方認可的方法。

給定一個哈希這樣的:

{ thing: { 
    thangs_attributes: { 
     'some_synethic_index' => { 
      attribute: value 
     }, 
     'some_other_index' => { 
      attribute: value 
     } 
    } 
} 

的想法基本上是允許在基於其外觀thang_attributes哈希鍵。

就是這樣。

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 

哪些應該建立一個嵌套的哈希爲thangs_attributes每個隨機索引鍵。或者,不安全地,您可以撥打params.require(:thing).permit!,這將允許任何和所有參數。

+0

你有沒有得到這個工作? – JoshL

+0

是的 - 這種方法的工作原理 - 儘管我最近一直在使用JSON模式來獲得更強大的解決方案。 – prater