Search code examples
ruby-on-railsruby-on-rails-4

Rails 4 permit nested hash with dynamic keys


Facing issues in permitting nested hash with dynamic keys in params. I have referred other similar questions on stack overflow but no luck so far. Any help is greatly appreciated. Below is the error raised.

ActionController::UnpermittedParameters found unpermitted parameters: volunteers_slots_attributes, sign_up_slots_attributes

{"event"=>{
"name"=>"ss", 
"volunteers_slots_attributes"=>{
"0"=>{"_destroy"=>"false", "needed_count"=>""},
"1"=>{"_destroy"=>"false", "needed_count"=>""},
... 
}, 
"sign_up_slots_attributes"=>{
"0"=>{"_destroy"=>"false", "title"=>"", "quantity"=>""}, 
"1"=>{"_destroy"=>"false", "title"=>"", "quantity"=>""}, 
"2"=>{"_destroy"=>"false", "title"=>"", "quantity"=>""},
 .... 
}, 
"supplies_note"=>""}}

Controller:

 def event_params
    params[:event].permit(:name,:supplies_note,
    :volunteers_slots_attributes,
    :sign_up_slots_attributes)
 end

Event Model:

  accepts_nested_attributes_for :sign_up_slots, allow_destroy: true, reject_if: :all_blank
  accepts_nested_attributes_for :volunteers_slots, allow_destroy: true, reject_if: :all_blank

Solution

  • You have to change your strong params like

    params
      .require(:event)
      .permit(
        :name,
        :supplies_note,
        volunteers_slots_attributes: [
          :_destroy,
          :needed_count
        ],
        sign_up_slots_attributes: [
          :_destroy,
          :title,
          :quantity
        ]
      )