Search code examples
ruby-on-railsstrong-parameters

strong_params removing id of accepts_nested_attributes_for models


I have the follow strong_params statement:

  def product_grid_params
    params.require(:product_grid).permit(:name,
      product_grid_locations_attributes: [:id, :grid_index, :item_id, :item_type, :short_name, :long_name]
    ).merge({ venue_id: params[:venue_id] })
  end

But my params and product_grid_params look like this:

(byebug) params
{"product_grid"=>{"product_grid_locations_attributes"=>[{"id"=>"5560d1f7a15a416719000007", "short_name"=>"shrt", "long_name"=>"Whiskey Ginger", "grid_index"=>73, "item_type"=>"product", "item_id"=>"9b97aa28-1349-4f60-a359-3907c8ac9a74"}]}, "id"=>"5560d1f7a15a416719000006", "venue_id"=>"5560d1f7a15a416719000005", "format"=>"json", "controller"=>"api/v2/manager/product_grids", "action"=>"update"}
(byebug) product_grid_params
{"product_grid_locations_attributes"=>[{"grid_index"=>73, "item_id"=>"9b97aa28-1349-4f60-a359-3907c8ac9a74", "item_type"=>"product", "short_name"=>"shrt", "long_name"=>"Whiskey Ginger"}], "venue_id"=>"5560d1f7a15a416719000005"}

You'll notice that in the params, the product_grid_location's id is present, but it gets filtered out in product_grid_params. What gives? I need that id there to update nested attributes.


Solution

  • Looks like this was because of an issue with Mongoid. The id I was passing in was a Moped::BSON::ObjectId, which strong_params refused to parse. I converted it to a string and everything was fine after that:

    params[:product_grid][:product_grid_locations_attributes].each { |location| location[:id] = location[:id].to_str }