简体   繁体   English

强大的参数允许使用数组

[英]Strong parameters permit Array of Arrays

I have data I am trying to POST that looks like { foo: [[:bar, 1], [:baz, 0]] } . 我有要尝试发布的数据,看起来像{ foo: [[:bar, 1], [:baz, 0]] }

How do I permit that using strong parameters ? 如何允许使用强参数 The closest I can get is 我能得到的最接近的是

params.permit(foo: [[]]) which returns {"foo"=>[]} params.permit(foo: [[]])返回{"foo"=>[]}

Maletor, Maletor,

it seems to me that the strong parameters can't handle array of array. 在我看来,强参数无法处理array数组。 I did read the code of it in github and it deals with Symbol, String and Hash . 我确实在github中阅读了代码,它处理了Symbol,String和Hash

For this case you'll have to handle with your own code. 对于这种情况,您必须处理自己的代码。

Basically: 基本上:

def permitted_params
  result = params.require(:model).permit(:attributes).to_h # No array of arrays or hashes
  result[:model][:array_of_arrays] = params[:model][:array_of_arrays]
  result
end

One step further, say you have a Model#json and you want to store model.json[:array_of_arrays] = [[]] : 更进一步,假设您有一个Model#json并且要存储model.json[:array_of_arrays] = [[]]

def permitted_params
  result = params.require(:model).permit(:attributes).to_h # No array of arrays or hashes
  result[:json] ||= {}
  result[:json].merge!(array_of_arrays: params[:model][:json][:array_of_arrays])
  result
end

Make sure you have permitted all your un-trusted params before you call to_h , and be careful what you merge in afterwards. 在调用to_h之前,请确保已允许所有to_h信任的参数,并请小心之后合并的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM