微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

参数包含要作为哈希值的数组

如何解决参数包含要作为哈希值的数组

| 我的
params
中有一个数组(来自
file_field,:multiple => true
),我想将其转换为散列,以便可以在create动作中为每个元素和过程建立关联的模型。 目前收到:
{\"gallery\"=>{\"name\"=>\"A gallery\",\"photos_attributes\"=>{\"0\"=>{\"image\"=>[#<1st Image data removed for brevity>,#<2nd Image data removed for brevity>]}}},\"commit\"=>\"Save\"}
我想将其转换为:
{\"gallery\"=>{\"name\"=>\"A gallery\",\"photos_attributes\"=>{\"0\"=>{\"image\"=>#<1st Image data removed for brevity>},\"1\"=>{\"image\"=>#<1st Image data removed for brevity>}}},\"commit\"=>\"Save\"}
考虑过这样的事情,但这显然是错误的:
i = 0
params[:gallery][:photos_attributes][\"0\"][:image].reduce({}) do |result,element|
  result[i++.to_s] = element
end
什么是“铁路方式”?     

解决方法

        您需要在每次迭代结束时返回结果哈希。
i = 0
params[:gallery][:photos_attributes][\"0\"][:image].reduce({}) do |result,element|
  result[(i += 1).to_s] = element
  result
end
    ,        从iOS设备接收数据时,我做过类似的事情。但是,如果我了解您想要的东西和您的模型的样子,那么要使嵌套属性起作用,您就不希望它看起来像:
{ \"photos_attributes\" => { \"0\" => <image1>,\"1\" => <image2>,... }
您希望它看起来像:
{ \"photos_attributes\" => [ <image1>,<image2>,... ] }
为此,您需要做的是:
params[\"gallery\"][\"photos_attributes\"] = params[\"gallery\"][\"photos_attributes\"][\"0\"][\"image\"]
现在,如果我误解了您的需求,就可以索取您所需要的东西(我用的不是9英镑,也就是10英镑),或者您可以使用水龙头:
i = 0
params[\"gallery\"][\"photos_attributes\"] = {}.tap do |hash|
  params[\"gallery\"][\"photos_attributes\"][\"0\"][\"image\"].each do |image|
    hash[i.to_s] = image
    i = i + 1
  end
end
IMO并没有很多。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。