2014-10-01 92 views
0

我有這個哈希迭代通過哈希散列內

"animal_images_attributes"=>{ 
"0"=>{ 
    "image_cache"=>"", 
    "image"=>#<ActionDispatch: : Http: : UploadedFile: [email protected]=#<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: [email protected]=#<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 

但這分配值true的所有圖像,而不是那些其實都是在iteration..Im希望這是有道理的

,如果我做

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 %> 

任何幫助表示讚賞在這一個作爲其導致有點絆腳石

回答

0

這將返回所有超過1兆字節的圖像。

big_images = images.select(&:image).select { |_k, image| File.size(image["image"].tempfile.path) > 1.megabyte } 
+0

這在我的方法嗎? – Richlewis 2014-10-01 08:13:21