【问题标题】:Strong parameters for model with has_many nested attributes具有 has_many 嵌套属性的模型的强参数
【发布时间】:2014-07-15 12:37:40
【问题描述】:

我怎样才能对这样的参数使用强参数:

{ 
  ... 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 sn-p 这样的普通许可样式:

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

它会在随机散列键上抛出未经允许的错误。

如何将强参数与 has_many 一起使用?

【问题讨论】:

    标签: ruby-on-rails-4 nested-attributes has-many strong-parameters


    【解决方案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!,这将允许任何和所有参数。

    【讨论】:

    • 是的 - 这种方法有效 - 尽管我最近一直在使用 JSON 模式来获得更强大的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多