views:

801

answers:

3

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  A: 

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 }
Jimmy Stenke
Just tried this, doesn't work.
bobthabuilda
hmm, which version of paperclip do you use (you can find the version in vendor/plugins/paperclip/lib/paperclip.rb)?
Jimmy Stenke
I just tried figured this out a few minutes ago. I came back here to report report my results and alas, they are nearly identical to yours. For anyone else with this problem you can also use the hash:Proc.new { |model| model[:image].nil? }
bobthabuilda
Except mine didn't work :) Corrected it now. Good that you solved it.
Jimmy Stenke
A: 

See also http://railscasts.com/episodes/134-paperclip, comment #106.

JF
A: 

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

works perfectly for me

Sytse