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

| 我的
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并没有很多。     

要回复问题请先登录注册