2

I'm working in Ruby on Rails and I'm trying to permit all values from a hash using Ruby's permit function. It seems rather simple, but I just cannot get this to work. I've already reviewed the references on permit, and answers to this SO question how to permit an array with strong parameters.

Here's my code

PERMITTED_PARAMS = [
  :OriginCity,
  :OriginState,
  { :PickupDates => {}}
].freeze
params = {"OriginCity"=>"Denver", "OriginState"=>"CO", "PickupDates"=>{"0"=>"2016-09-30"}}
filtered_params = params.permit(PERMITTED_PARAMS)

And, the resulting value for filtered_params is

{"OriginCity"=>"Denver", "PickupDates"=>{}}

While the desired value for filtered_params is

{"OriginCity"=>"Denver", "PickupDates"=>{"0":"2016-09-30"}}

Any advice on how to obtain the desired value by changing PERMITTED_PARAMS?

Community
  • 1
  • 1
Craig
  • 456
  • 5
  • 14

1 Answers1

0

You want to permit all values in a hash, not an array, which is different from the example you linked to.

Try this:

PERMITTED_PARAMS = [
  :OriginCity,
  :OriginState
].freeze
params = {"OriginCity"=>"Denver", "OriginState"=>"CO", "PickupDates"=>{"0"=>"2016-09-30"}}
filtered_params = params.permit(PERMITTED_PARAMS).tap do |whitelisted|
  whitelisted[:PickupDates] = params[:PickupDates]
end

See also: Strong parameters: allow hashes with unknown keys to be permitted

Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
  • `:PickupDates => params[:PickupDates].try(:keys)` might be better, then you'd be able to easily filter the keys for things that match what you're expecting: `:PickupDates => params[:PickupDates].try(:keys).to_a.select { |k| Integer(k) rescue nil }` for example. I can't find a way to give strong params a regex to match the keys so you're stuck doing it by hand. – mu is too short Sep 29 '16 at 21:56
  • Great! And yes accepting all params is a bit permissive, but out of the box strong parameters doesn't do much more for you. If you're concerned you can filter only keys you want, etc. but the code will get more complicated... – Chris Salzberg Sep 29 '16 at 22:21