timpone
timpone

Reputation: 19979

to_hash and strong_parameters for Rails 5.1 with an array of items

I have the following params declaration:

   def line_item_params
     params.require(:line_items).map do |p|
       ActionController::Parameters.new(p.to_hash).permit(:quantity, :price, :menu_item_id)
     end
    end

but get the following error:

Method to_hash is deprecated and will be removed in Rails 5.1, as ActionController::Parameters no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited. Instead, consider using one of these documented methods which are not deprecated: http://api.rubyonrails.org/v5.0.1/classes/ActionController/Parameters.html

I am just posting an array of items. How should this be handled?

Upvotes: 0

Views: 770

Answers (1)

max
max

Reputation: 102423

def line_item_params
  # just to raise ActionController::ParameterMissing if key is missing
  params.require(:line_items) 
  # this is the actual whitelist
  params.permit(line_items: [:quantity, :price, :menu_item_id])
end

You can whitelist an array of objects by passing a hash option to .permit with an array containing the keys to whitelist for the nested objects.

Upvotes: 1

Related Questions