geeku
geeku

Reputation: 65

Is it possible to make an attachment optional in paperclip?

Here's how I am using paperclip in my model:

has_attached_file :photo,
  styles: {
    display: {
      geometry: "146x153#",
      format: :jpg,
    },
    message: {
      geometry: "48x48#",
      format: :jpg,
    }
  }

validates_attachment_content_type :photo, content_type: ['image/jpeg', 'image/png','image/gif']
validates_attachment_size         :photo, less_than:    2.megabytes, unless: :record_is_new?

It works fine, however, I want to make the image upload optional i.e. if the user does not wish to upload a picture, the validation should not apply.

Upvotes: 3

Views: 830

Answers (2)

geeku
geeku

Reputation: 65

Solved this, the model had this validation: validates_attachment_presence: photo that i completely overlooked.

Upvotes: 2

oldhomemovie
oldhomemovie

Reputation: 15129

Try validation conditionally, adding this to validations:

validates_something_on :photo, ..., unless: Proc.new { |record| record[:image].nil? }

Result:

validates_attachment_content_type :photo, content_type: ['image/jpeg', 'image/png','image/gif'], unless: Proc.new { |record| record[:image].nil? }
validates_attachment_size         :photo, less_than:    2.megabytes,                             unless: Proc.new { |record| record[:image].nil? }

Upvotes: 0

Related Questions