简体   繁体   中英

how to permit one of the parameters to be arbitrary hash using strong_parameters?

I have a model with one of the fields being serialise :config, JSON .

it should permit any hash as a value. But I can't quite see a clean way to do it with strong_parameters .

my current solution is:

def resource_params
  p = params.require(:model)
  config = dp.slice(:config).permit!
  p.delete(:config)
  [p.permit(:foo, :bar, ...).merge(config)]
end

From strong_params gem page

To whitelist an entire hash of parameters, the permit! method can be used

params.require(:log_entry).permit!

And also

If you want to make sure that multiple keys are present in a params hash, you can call the method twice:

params.require(:token)
params.require(:post).permit(:title)

but I'm no expert on that matter.

You have to use whitelisting:

def resource_params
  params.require(:model).permit(:foo, :bar, ...).tap do |whitelisted|
    whitelisted[:config] = params[:model][:config]
  end
end

You can find it here: http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters search for "4.5.4 Outside the Scope of Strong Parameters"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM