Tuesday, 17 July 2012

paperclip image validation

Hi,

I am using paperclip gem  for image uploading in rails application.

In my application I have made photo model to work with polymorphic association  i.e to store photos related content in single table to make application look clean.

So I have associated in user model as below

Class User << ActiveRecord

has_many :photos, :as => :photoable, :dependent => :destroy

end

In photo model

class Photo < ActiveRecord::Base
  belongs_to :photoable, :polymorphic => true

  validates_attachment_presence :image
  validates_attachment_size :image, :less_than => 5.megabyte
  validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/png', 'image/gif']

end

I have faced issue at a satuation where I need to have photo field and it should validate only when there was image uploaded. Due to present validations its trowing validation error's while saving the user data.

I have solved the above issue by adding conditional validations in photo model as below

 validates_attachment_presence :image, :if => lambda { |images| !images.image_file_name.nil?}


The above validation will be invoked only when image was uploaded.


Thank You,
Uma Mahesh.

No comments:

Post a Comment