Craig Craig - 2 months ago 5
Ruby Question

How to permit all values from a hash

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?

Answer

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

Comments