Dynamic hash field in Mongoid using strong parameters

邮差的信 提交于 2019-12-03 15:10:23

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

If necessary nested attributes can also be permitted as follows:

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

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 to for example the values param, you can use it like this:

def item_params
  params.require(:item).permit(values: permit_recursive_params(params[:item][:values]))
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!