【问题标题】:Use single attachment for video/image in paperclip对回形针中的视频/图像使用单个附件
【发布时间】:2011-11-01 06:35:31
【问题描述】:

我正在使用回形针上传文件(视频和图像)。 视频和图片使用了相同的附件(来源)。

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 时

我怎样才能做到这一点? 任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails-3 validation file-upload paperclip


    【解决方案1】:

    所以我终于找到了解决方案。 我为同一个添加了 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
    

    【讨论】:

    • 不错的解决方案。顺便提一句。您每条记录保留一个附件,在这种情况下不应将类名称为中等?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2013-10-13
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多