Rails - Paperclip validating attachment size when it shouldn't be?

寵の児 提交于 2019-12-31 21:42:12

问题


I've got a rails model using Paperclip that looks like this:

  has_attached_file :image, :styles => { :normal => ['857x392#', :png] },
                    :url => '/assets/pages/:id/:basename.:extension',
                    :path => ':rails_root/public/assets/pages/:id/:basename.:extension'

  validates_attachment_size :image, :less_than => 2.megabytes

When attempting to create a record of this model without an attachment to upload, the validation error is returned:

There were problems with the following fields:

* Image file size file size must be between 0 and 2097152 bytes.

I've tried passing both :allow_blank => true and :allow_nil => true after the validation statement in the model, but neither have worked.

How can I allow the :image parameter to be blank?


回答1:


validates_attachment_size :image, :in => 0.megabytes..2.megabytes

works now




回答2:


validates_attachment_size :image, :less_than => 25.megabytes, 
                          :unless => Proc.new {|m| m[:image].nil?}

works perfectly for me




回答3:


Paperclip's validation only checks the range, and doesn't care about the :allow_nil => true

What you can do is try to set :min => nil or :min => -1, maybe that will work.

Update: This will not work in the latest version of Paperclip since they have changed how validations work. What you could try instead is:

validates_attachment_size :image, :less_than => 2.megabytes, 
   :unless => Proc.new {|model| model.image }



回答4:


Try the following code.

validate :image_present

def image_present
  if image.present? && image_file_size < 2.megabytes
    errors.add(:file_size, "file size must be between 0 and 2 megabytes.")
  end
end


来源:https://stackoverflow.com/questions/2045212/rails-paperclip-validating-attachment-size-when-it-shouldnt-be

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