2012-03-17 92 views
1

我有一個模型3個附件,請幫我幹。DRY和回形針

class Somename < ActiveRecord::Base 

has_attached_file :picture, :url => "/uploads/p/:id/picture.:extension" 
validates_attachment_presence :picture 
validates_attachment_content_type :picture, :content_type => ['image/jpeg', 'image/png'] 

has_attached_file :another_picture, :url => "/uploads/p/:id/another_pictures/:style/another_picture.:extension", 
    :styles => { main: '720x480#', small: '480x311#' } 
validates_attachment_presence :another_picture 
validates_attachment_content_type :another_picture, :content_type => ['image/jpeg', 'image/png'] 

has_attached_file :last_one, :url => "/uploads/p/:id/last_one.:extension" 
validates_attachment_presence :last_one 
validates_attachment_content_type :last_one, :content_type => ['image/jpeg', 'image/png'] 
end 

特別驗證。爲什麼我不能做這樣的事情:

validates_attachment_presence :picture, :another_picture, :last_one 

謝謝!

回答

0

你可以嘗試這樣的事情(不知道是否會工作完全按原樣用回形針,但可能應該很好地工作):

(見source code of validates_attachment_presence,它會更清楚怎麼回事)

module PaperclipEnhancement 
    def validates_attachments_presence(*attributes) # note the plural 'attachments' 
    attributes.each do |attribute| 
     validates_attachment_presence attribute #call the original paperclip validator 
    end 
    end 
end 

class Somename < ActiveRecord::Base 
    extend PaperclipEnhancement 
    validates_attachments_presence :picture1, :picture2 
end