Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic hash field in Mongoid using strong parameters

So there doesn't appear to be any clean way to generically allow Hash field with strong parameters. This may of course be a strong parameters issue but I'm curious if there is a workaround. I have a model with some fields...

field :name, type: String
field :email, type: String
field :other_stuff, type: Hash, default: {}

Now I could just permit everything:

params.require(:registration).permit!

But that isn't really a great idea and what I'd like to do is something like...

params.require(:registration).permit(:name, :email, { other_stuff: {} })

However this doesn't seem to be possible with strong parameters, it isn't possible to just whitelist a hash as a property (yay for SQL centric ActiveRecord APIs!). Any ideas how this might be done, or is my best bet to submit a Rails patch to allow for this scenario.

like image 733
Chris Nicola Avatar asked Aug 27 '13 01:08

Chris Nicola


1 Answers

Ok, after researching this, I found an elegant solution that I will start using too:

params.require(:registration).permit(:name).tap do |whitelisted|
  whitelisted[:other_stuff] = params[:registration][:other_stuff]
end

source: https://github.com/rails/rails/issues/9454#issuecomment-14167664

like image 104
Arthur Neves Avatar answered Oct 11 '22 01:10

Arthur Neves