Validate attachment content type Paperclip in Rails 2 application
In my Rails 2 application, images for products are uploaded using Paperclip as a plugin. I need to restrict the image types to jpeg and png and also allow saving of product even if image is not uploaded.
The current code is
has_attached_file :master_image, :url => "/images/products/:id/private/master.img", :path => ":rails_root/public/images/products/:id/private/master.img" validates_attachment_content_type :master_image, :content_type => ['image/png', 'image/jpg'] , :message => "image must be jpg or png." , :allow_nil => true
I added :allow_nil => true but it is not working.
I am getting image must be jpg or png when trying to save without image.
Is it possible to do the validation only if an attachment is included?
You are getting image must be jpg or png when trying to save without image because if the image is not present which implies that the content type is also missing i.e. they are not jpg or png.
To accomplish your task, you can add a custom validator where first you will check if the image is present and if yes, only then you will check the :content_type of the image.
Add these in your Product Model:
validate :master_image_type_present def master_image_type_present if master_image.present? && !(['image/png', 'image/jpg', 'image/jpeg'].include? master_image_content_type) errors.add(:content_type, "invalid content type") end end
And, your validation will work as expected.