Use single attachment for video/image in paperclip

為{幸葍}努か 提交于 2019-12-18 12:03:10

问题


I am using paperclip for uploading file ( video and images). Have used the same attachment(source) for both video and images.

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

Now I wanted to display different error messages in different cases.

  1. When uploading file is image type but not the jpg/png/jpeg/gif.
  2. When uploaded file is video type but not the mp4

How can i achieve this ? Any help would highly appreciated.


回答1:


So finally I got the solution. I added 2 conditional validation for the same

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


来源:https://stackoverflow.com/questions/7149985/use-single-attachment-for-video-image-in-paperclip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!