0

我想在我的應用程序用戶能夠上傳文件與回形針尺寸驗證錯誤4

至少width:800pxheight: 550px

創建的應用程序/模型/ dimensions_validator.rb文件 和代碼

class DimensionsValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
    dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path) 
    width = options[:width] 
    height = options[:height] 

    record.errors[attribute] << "Width must be at least #{width}px" if dimensions.width < width 
    record.errors[attribute] << "Height must be at least #{height}px" if dimensions.height < height 
    end 
end 

在我應用程序/模型/ gig.rb模型

validates :image, :dimensions => { :width => 800, :height => 550 } 

問:當我點擊提交按鈕,實際上並沒有選擇任意圖片,它得來的錯誤說undefined method "path" for nil:NilClass 和它在紅色標誌着4號線是dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path)

也許我需要一個代碼,以檢查圖像存在,像if image.present?但瓦特我會在這裏包括嗎?我在演出模式validates_attachment_presence :image

這已經使用是錯誤 error

這是我GigsController#更新

def update 
    if @gig.update(gig_params) 
     redirect_to @gig, notice: "Gig was successfully updated" 
    else 
     render "edit" 
    end 
    end 
+0

對不起,你的意思是在第一個o新來的?你能否寫下它作爲答案。謝謝。 –

+0

你能檢查你的控制器是否允許params包含'image'?您還可以在日誌輸出中查找類似'Unpermitted parameter:image'的內容。 – Curtis

+0

是的,它是允許的。並且在日誌中,我得到了 NoMethodError(未定義的方法路徑爲零:NilClass): app/models/dimensions_validator.rb:3:在'validate_each' app/controllers/gigs_controller。rb:71:'update' –

回答

3

試試這個。

validates :image, :unless => "image.queued_for_write[:original].blank?", dimensions: { width: 800, height: 550 } 
+0

謝謝。爲什麼這個工作? – Undistraction

0

我相信你可以添加其他條件,您的驗證。所以,你可以嘗試添加allow_blankif條件:

validates :image, dimensions: { width: 800, height: 550 }, allow_blank: true 

或可能:

validates :image, dimensions: { width: 800, height: 550 }, if: Proc.new {|gig| gig.image? } 
+0

它不起作用,它給出了絕對相同的錯誤,但是當我創建一個新的演出時,它與我當前的設置一起工作,但當我更新它時不工作。請參閱我編輯的問題,最後一個圖片。 –

+0

我試圖在本地重新創建您的情況。通過在自定義驗證程序的開始處放置一個'byebug'語句,我能夠驗證驗證程序是否*以上述任一方式執行*。 – Curtis

0

它可以使用這個gem圖像寬度和高度的驗證與Papercliphttps://github.com/evedovelli/image_validators

將它添加到您的包:

gem 'image_validators' 

並添加驗證規則到模型:

validates :image, dimensions: { greater_than_or_equal_to: { width: 800, height: 550 } }