2011-08-22 4 views
9

파일 (비디오 및 이미지) 업로드 클립 클립을 사용하고 있습니다. 비디오 및 이미지 모두에 동일한 첨부 파일 (원본)을 사용했습니다.클립 클립의 비디오/이미지에 단일 첨부 사용

class Media < ActiveRecord::Base 
    belongs_to :memory 
    validates_attachment_presence :source 
    validates_attachment_content_type :source, 
    :content_type => ['video/mp4', 'image/png', 'image/jpeg', 'image/jpg', 'image/gif'] 
end 

이제 다른 경우에 다른 오류 메시지를 표시하려고합니다.

  1. 업로드하는 파일이 이미지 유형이지만 jpg/png/jpeg/gif가 아닌 경우.
  2. 업로드 된 파일은 비디오 형식이 아니라 MP4

입니다 내가 어떻게 이것을 달성 할 수 있습니까? 도움을 주시면 감사하겠습니다.

답변

22

결국 나는 해결책을 얻었습니다. 동일 조건에 2 가지 조건부 유효성 검사를 추가했습니다.

class Media < ActiveRecord::Base 
    belongs_to :memory 
    validates_attachment_presence :source 
    validates_attachment_content_type :source, 
    :content_type => ['video/mp4'], 
    :message => "Sorry, right now we only support MP4 video", 
    :if => :is_type_of_video? 
    validates_attachment_content_type :source, 
    :content_type => ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'], 
    :message => "Different error message", 
    :if => :is_type_of_image? 
    has_attached_file :source 

    protected 
    def is_type_of_video? 
    source.content_type =~ %r(video) 
    end 

    def is_type_of_image? 
    source.content_type =~ %r(image) 
    end 
end 
+0

좋은 해결책입니다. btw. 당신은 레코드 당 하나의 첨부 파일을 유지하고, 클래스 이름은이 경우 매체라고해서는 안됩니까? – res

관련 문제