【问题标题】:Validate Attachment Content Type Paperclip验证附件内容类型回形针
【发布时间】:2010-07-05 19:56:58
【问题描述】:

是否可以在paperclip 中强制执行“内容类型”验证而不强制执行“存在”验证(即允许空白)?我目前有:

class Person < ActiveRecord::Base
  has_attached_file :picture
  validates_attachment_content_type :picture, :content_type => ['image/jpeg', 'image/jpg', 'image/png']
end

但是,如果不存在附件,则此操作会失败。例如:

>> @person = Person.new
>> @person.save
>> @person.errors.first
=> ["picture_content_type", "is not one of image/jpeg, image/jpg, image/png"]

是否可以仅在包含附件时进行验证。

【问题讨论】:

    标签: ruby-on-rails paperclip


    【解决方案1】:

    我不确定那个方法是你失败的原因;这是我的简单课程

    class Image < ActiveRecord::Base
      has_attached_file :photo, {
                :styles => { :large => "700x400#", :medium=>"490x368#", :thumbnail=>"75x75#" },
                :default_url => "/images/thumbnail/blank-recipe.png"}
      validates_attachment_content_type :photo, :content_type => /image/ 
    end
    

    那么,如果我:

    Image.new.valid?
    #this is true
    

    不过,您可能正在进行其他回形针验证。可以发一个简单的例子吗?

    【讨论】:

    • 我稍微更新了上面的示例代码。当我执行“Person.new.valid?”结果是假的。我正在运行 Rails 2.3.8 和 Paperclip 2.2.15。
    • 如果我理解正确:content_type =&gt; /image/ 表示图像文件类型列表。你知道这个列表包括什么,它存储在 Paperclip 代码中的什么位置,以及它是否存在于其他类型的文件(如文档)中?
    • 注意} in :default_url =&gt; "/images/thumbnail/blank-recipe.png"} 这将导致错误。
    【解决方案2】:

    工作示例

    在以下模型中,只有 image/png、image/gif 和 image/jpeg 是图片附件的有效内容类型。

    class Photo
      has_attached_file :image
      validates_attachment_content_type :image, 
                                        :content_type => /^image\/(png|gif|jpeg)/
    end
    

    规格

    describe Photo do
      it { should validate_attachment_content_type(:image).  
                  allowing('image/png', 'image/gif', 'image/jpeg').      
                  rejecting('text/plain', 'text/xml', 'image/abc', 'some_image/png') }
    end
    

    更多信息

    您还可以查看负责进行验证的 AttachmentContentTypeValidator 类。

    或者看看它的 tests 包含更多示例。

    【讨论】:

      【解决方案3】:

      validates_content_type 在它的选项哈希中接受:if =&gt; Proc.new{|r| !r.content_type.blank?},也许这会解决你的问题。

      http://rdoc.info/github/thoughtbot/paperclip#

      【讨论】:

        【解决方案4】:

        这对我有用;

        validates_attachment :image1, :presence => true,
                                 :content_type => { :content_type => "image/jpg" },
                                 :size => { :in => 0..10.kilobytes }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多