[英]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.