简体   繁体   English

参数包含一个想要成为哈希的数组

[英]Params contain an array that wants to be a hash

I have an array (coming from a file_field, :multiple => true ) in my params that I want to turn into a hash so I can build associated models for each element and process in my create action. 我有一个数组(从即将到来file_field, :multiple => true )在我的params ,我想转成散列,所以我可以建立在我创建行动的每个元素和工艺相关的模型。

Currently receiving: 目前收到:

{"gallery"=>{"name"=>"A Gallery", "photos_attributes"=>{"0"=>{"image"=>[#<1st Image data removed for brevity>, #<2nd Image data removed for brevity>]}}}, "commit"=>"Save"}

I'd like to turn it into something like: 我想将其转换为:

{"gallery"=>{"name"=>"A Gallery", "photos_attributes"=>{"0"=>{"image"=>#<1st Image data removed for brevity>}, "1"=>{"image"=>#<1st Image data removed for brevity>}}}, "commit"=>"Save"}

considered something like this but it's clearly wrong: 考虑过这样的事情,但这显然是错误的:

i = 0
params[:gallery][:photos_attributes]["0"][:image].reduce({}) do |result, element|
  result[i++.to_s] = element
end

What's the "Rail's Way"? 什么是“铁路方式”?

You need to return the result hash at the end of each iteration. 您需要在每次迭代结束时返回结果哈希。

i = 0
params[:gallery][:photos_attributes]["0"][:image].reduce({}) do |result, element|
  result[(i += 1).to_s] = element
  result
end

I've done something similar when receiving data from an iOS device. 从iOS设备接收数据时,我做过类似的事情。 But, if I understand what you want and what your model(s) look like, to get nested attributes to work you don't want it to look like: 但是,如果我了解您想要的东西和您的模型的样子,那么要使嵌套属性正常工作,您就不希望它看起来像:

{ "photos_attributes" => { "0" => <image1>, "1" => <image2>, ... }

You want it to look like: 您希望它看起来像:

{ "photos_attributes" => [ <image1>, <image2>, ... ] }

And to do that all you need to do is: 为此,您需要做的是:

params["gallery"]["photos_attributes"] = params["gallery"]["photos_attributes"]["0"]["image"]

Now, if I've misunderstood what you need, to get what you've asked for what you have might work (I don't use much reduce aka inject ) or you could use tap: 现在,如果我误解了您的需求,可以得到您所要求的东西(我不使用太多reduce aka inject ),也可以使用tap:

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

Not a whole lot better IMO. IMO并没有很多。

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

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