I have a rails application that stores a serialized hash in a field called properties
.
The hashes keys are unknown though, so I don't know of a way to allow this with strong parameters.
When googling, I found this: https://github.com/rails/rails/issues/9454, but I couldn't figure out exactly what a solution would be.
So basically, my question is: How can you configure strong parameters to allow hashes with unknown keys?
Thanks for all help!
None of these answers worked for me (using Rails 4.2.4), so I figured out the following workaround:
def product_params properties_keys = params[:product][:properties].keys params.require(:product).permit(:title, :description, properties: properties_keys) end
Hope that helps someone.
Your need is completely opposite of objective of strong parameter, when we define strong parameter then basically we are going to whitelist the coming params.
and here in your case we exactly don't know the keys, so there is no need to put strong parameter check over there. that will solve your problem.
You can use a hash instead of a symbol and define what sub-properties are allowed. This can be seen in the source here:
https://github.com/rails/rails/blob/bdc73a438a97f2e0aceeb745f4a95f95514c4aa6/actionpack/lib/action_controller/metal/strong_parameters.rb#L522
e.g.
If you have no idea what is going to be in
properties
you could use .slice. Note this will accept anything nested in any of the other fields too.e.g.
These approaches will work on the following params:
I've confirmed these will work on
Rails 4.2.6
I recently had this same issue and I solved it using @fxn's method from https://github.com/rails/rails/issues/9454
For product with
properties
as hash, solved it asIf you use
:raise
instead of:log
forconfig.action_controller.action_on_unpermitted_parameters
in yourenvironment
then remember to removeproperties
fromparams
before callingpermit
. Then the method will be