Dynamic hash field in Mongoid using strong parameters

Thus, there seems to be no clean way to general resolution of the Hash field with strong parameters. Of course, this may be a problem with strong parameters, but I'm curious if there is a way around this. I have a model with some fields ...

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

Now I can simply resolve everything:

 params.require(:registration).permit! 

But this is not a good idea, and I would like to do something like ...

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

However, this is not possible with strong parameters, it is impossible to simply reinstall the hash as a property (yay for SQL-oriented ActiveRecord APIs!). Any ideas on how to do this, or is this the best attempt to send a Rails patch to resolve this scenario.

+6
source share
3 answers

Well, after learning 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

+8
source

If necessary, nested attributes can also be resolved as follows:

 def create_params params[:book]["chapter"].permit(:content) end 
0
source

For a field that allows nested hashes, I use the following solution:

 def permit_recursive_params(params) params.map do |key, value| if value.is_a?(Array) { key => [ permit_recursive_params(value.first) ] } elsif value.is_a?(Hash) || value.is_a?(ActionController::Parameters) { key => permit_recursive_params(value) } else key end end end 

To apply it, for example, to the values parameter, you can use it as follows:

 def item_params params.require(:item).permit(values: permit_recursive_params(params[:item][:values])) end 
0
source

Source: https://habr.com/ru/post/952554/


All Articles