Search code examples
ruby-on-railshashattributesstrong-parameters

How do I get a Hash attribute value past Strong Parameters in Rails?


I am trying to use a serialized hash attribute in an model. I have the form set up, so it submits the data properly. This is the hash I get:

Parameters: {"utf8"=>"√", "authenticity_token"=>"...", "product"=>{"name"=>"h", "description"=>"", "pricing_hash"=>{"Unit"=>"0.0", "Gram"=>"10.0", "Ounce"=>"200.0"}}, "commit"=>"Create Product"}

The important value is :pricing_hash, and the data is what it should look like. But, when I submit, it does not save the hash, and I get the console message:

Unpermitted parameters: Unit, Gram, Ounce

I can hack the controller, to allow the values I need (Unit, Gram, etc.), though I would like to do this dynamically, to extend pricing options in the future, but I cannot figure out how to form the controller method to permit those params.


Solution

  • Your strong params method should look something like this:

    params.require(:product).permit(:name, :description, 
                                     pricing_hash: [:Unit, :Gram, :Ounce])
    

    I'm not 100% sure if the capitalization makes a difference. However, the hash MUST be at the end of the list. For instance, you cannot put :name after that or it would throw an error.