uccblack
uccblack

Reputation: 107

Unpermitted Parameters with Hashes in Rails

I have a hash field in my Rails model and am attempting to update it. The attribute, detail, was first generated through a migration as a text type. Afterwords, in my model, it was set as a hash through the store :detail property

class Request < ActiveRecord::Base
    store :detail
end

My strong_params are as such:

params.require(:request).permit(:name, :action, :detail => {})

However, when my Parameters go through as

Parameters: {"request"=>{"name"=>"temp", "action"=>"create", "detail"=>{"test"=>"fdsf"}}}

I am told that there is an Unpermitted parameter: test, despite the test parameter being part of the detail hash.

How do I fix this? Thanks!

Upvotes: 4

Views: 2316

Answers (2)

The F
The F

Reputation: 3714

This (rather old) issue tackles your problem quite interestingly

Considering your hash consists of more values than :test you could try the solution with .tap

params.require(:request).permit(:name, :action).tap do |whitelisted|
  whitelisted[:detail] = params[:request][:detail]
end

Or the somewhat less dynamic:

params.require(:request).permit(:name, :action, :detail => [:test])

This blogpost sums up different approaches.

edit

You need your detail column to be of type 'text' to be able to save the hash as a string. In your Request model add this to the top:

serialize :detail

as it will allow to interpret the stringified :detail as a hash

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

params.require(:request).permit(:name, :action, detail: [:test])

Another option (e. g. if you do not know the possible field names in advance) would be to serialize the detail to json string on client side, accept it as string and deserialize to a hash afterwards.

Upvotes: 7

Related Questions