2010-05-10 40 views
6

我使用回形針來處理我的文件上傳,並且在一種情況下,我不希望該文件是強制性的。但是,我確實想確保它是一種特定的文件類型。回形針 - 驗證文件類型但不存在

我有這樣的:

class TestModel < ActiveRecord::Base 
    #stuff 
    has_attached_file :sound #etc... 
    validates_attachment_content_type :sound, :content_type => ['audio/mp3', 'application/x-mp3'] 
end 

當我不存在的聲音文件,它告訴我它是不是有效的內容類型之一。我已經嘗試在:content_type陣列中添加'',這也不起作用!

我也嘗試爲:if屬性創建一個lambda過程,但是我不能讓它在沒有某種錯誤的情況下運行。

這裏有什麼缺失嗎?

+0

我問作爲類似的問題一會兒回http://stackoverflow.com/questions/2257041/smarter-paperclip-validations - 我得到它與proc一起工作。也許它會幫助你 – stephenmurdoch 2010-06-05 05:07:10

回答

0

塊我的模型:

has_attached_file :logo, :styles => { :medium => ["300x300>", :png], :thumb => ["100x100>", :png] } 
    validates_attachment_size :logo, :less_than => 2.megabytes 
    validates_attachment_content_type :logo, :content_type => ['image/jpeg', 'image/png', 'image/gif'] 

,如果我不提供圖像文件,@ obj.update_attributes(..)引發任何錯誤,但如果我提供了一個文件驗證。也許你使用舊式回形針?

gem list | ack paperclip 
paperclip (2.3.1.1) 
+0

我有版本2.3.2並有同樣的問題:( – 2010-05-22 00:20:01

4

我想你可以嘗試'條件驗證'條件是如果文件存在?

class TestModel < ActiveRecord::Base 
    #stuff 
    has_attached_file :sound #etc... 
    validates_attachment_content_type :sound, :content_type => ['audio/mp3', 'application/x-mp3'], :if => :sound_attached? 

    def sound_attached? 
    self.sound.file? 
    end 
end 
+0

我意識到我必須從Paperclip 2.3.1.1升級到Paperclip 2.3.2後執行此操作 – 2010-06-01 22:33:50

0

討論首先讓我說,我是新來的都Ruby和Rails。其次,我不知道這是否可以應用於音頻文件,但使用圖像我只是設置了一個默認圖像,以便以某種方式存在與每個記錄相關的照片。

has_attached_file :photo, styles: { small: "64x64", med: "100x100", large: "200x200" }, default_url: "/images/no-image-available.png"