Rails 4 permit any keys in the hash

329 views Asked by At

I pass a params like this

{
  "utf8" => true,
  "supply" => {
    "items" => { 111 => 112, 89 => 10},
    "another_params" => "something"
  }
}

My supply_params are:

params.fetch(:supply, {}).permit(:another_params, items: {})

But I get an unpermitted parameters 111 and 89. How can I make items permit all kinds of keys?

2

There are 2 answers

2
steve klein On BEST ANSWER

This thread in github provides a solution:

def supply_params
  params.require(:supply).permit(:another_params).tap do |whitelisted|
    whitelisted[:items] = params[:supply][:items] if params[:supply][:items]
  end
end

The idea is to explicitly permit any known attributes which are needed and then tack on nested attributes.

2
Alex Antonov On

According to the @steve klein link to github issue, this is considered as a good solution:

params.permit(:test).tap do |whitelisted|
  whitelisted[:more] = params[:more]
end