使用强大参数的Mongoid中的动态哈希字段 [英] Dynamic hash field in Mongoid using strong parameters

查看:106
本文介绍了使用强大参数的Mongoid中的动态哈希字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,似乎没有任何干净的方法可以普遍允许具有强参数的Hash字段.这当然可能是一个很强的参数问题,但是我很好奇是否有解决方法.我有一个模型,其中包含一些字段...

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:{}})

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

但是,使用强参数似乎不可能做到这一点,但不可能仅将哈希表列入属性(对于以SQL为中心的ActiveRecord API来说是这样!).关于如何完成此操作的任何想法,或者我最好的选择是提交Rails补丁以适应这种情况.

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.

推荐答案

好的,在研究了这一点之后,我发现了一个优雅的解决方案,我也将开始使用它:

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

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

这篇关于使用强大参数的Mongoid中的动态哈希字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆