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?

Answers


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.


Need Your Help

how to implement Java socket communication on Tomcat

java android sockets

I currently have an TCP Java socket communication implementation in which I have a server that is listening to a port (let's say port 5478). Then I need an Android client to remotely connect to the...

How to databind a repeater from stored procedure?

asp.net vb.net repeater data-binding

I'm trying to databind my repeater but so far not having any luck. Anyone think that can show me where I'm going wrong? I have two functions at the moment by following some tutorials/examples but...