Search code examples
ruby-on-rails-4nested-attributeshas-manystrong-parameters

Strong parameters for model with has_many nested attributes


How can I use strong parameters for params like this:

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

If I use the normal permit style like the ff snippet:

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

it would throw and non-permitted error on the random hash key.

How do i use strong parameters together with has_many?


Solution

  • There is no officially sanctioned method for doing this other than the obvious, kind of ugly one.

    Given a hash like this:

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

    The idea is basically to allow the keys in the thang_attributes hash based on their appearance.

    Something like this.

    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
    

    Which should set up a nested hash for each random index key in thangs_attributes. Alternatively, and unsafely, you could call params.require(:thing).permit! which will permit any and all parameters.