[英]Iterate through hash within a hash
我有这个哈希
"animal_images_attributes"=>{
"0"=>{
"image_cache"=>"",
"image"=>#<ActionDispatch: : Http: : UploadedFile: 0x0000000673efa0@tempfile=#<Tempfile: /tmp/RackMultipart20140930-17710-u3g1hm>,
@original_filename="bryony_portfolio.png",
@content_type="image/png",
@headers="Content-Disposition: form-data; name=\"animal[animal_images_attributes][0][image]\"; filename=\"bryony_portfolio.png\"\r\nContent-Type: image/png\r\n">,
"_destroy"=>"false"
},
"1412109521172"=>{
"image_cache"=>"",
"image"=>#<ActionDispatch: : Http: : UploadedFile: 0x0000000673ea78@tempfile=#<Tempfile: /tmp/RackMultipart20140930-17710-1670i9p>,
@original_filename="vandals_portfolio.png",
@content_type="image/png",
@headers="Content-Disposition: form-data; name=\"animal[animal_images_attributes][1412109521172][image]\"; filename=\"vandals_portfolio.png\"\r\nContent-Type: image/png\r\n">,
"_destroy"=>"false"
}
}
}
我想遍历每个图像并获得“图像”的文件大小,如果文件大小超过1mb,我想为表示已结束的图像(键)使用一个标识符。 到目前为止,我已经建立了这个
class AnimalsController < ApplicationController
before_action :max_file_size, only: [:create]
def max_file_size
image = params[:animal][:animal_images_attributes]
image.each do |k,v|
img_cache = v["image_cache"]
img = v["image"]
if img
tempfilepath = img.tempfile.path
file_size = File.size(tempfilepath)
if file_size > 1.megabytes
@largeImage = true
else
@largeImage = false
end
end
end
end
end
但这是为所有图像分配真实值,而不是迭代中实际存在的值。
如果我做
if file_size > 1.megabytes
ap(file_size)
end
我将此输出到控制台
1718186
1141251
这是正确的,因为在我的示例中,我添加了1MB以上的两个图像。
所有这些的想法基本上是针对每个大于1mb的图像说,然后有条件地添加此类:
<%= f.fields_for :animal_images do |build| %>
<div class="<%= 'large_image' if @largeImage = true %> form-group has-feedback">
<% end %>
这将返回所有超过1 MB的图像。
big_images = images.select(&:image).select { |_k, image| File.size(image["image"].tempfile.path) > 1.megabyte }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.