Reputation:
I have a rails model in which an image is uploaded using Paperclip.
I have added validation of size for the image.
validates_attachment-size :image, less_than => 5.megabytes
When trying to save the model when there is no attachment it validates the image which is absent and fails the save.
I need to save the model if there is no image and the validation should work only when there is an image.
Upvotes: 1
Views: 993
Reputation: 34338
First of you have a typo in your code. validates_attachment-size
should be validates_attachment_size
.
You wanted to do:
validates_attachment_size :image, less_than => 5.megabytes
This built in helper would work normally. But, this validation will force the validation of an actual attachment, means it won't work if the image is not present.
So, if you want to be sure if an image is present, you can add a custom validator
where you will check the image presence. Like this:
validate :image_presence_and_size
def image_presence_and_size
if image.present? && image_file_size < 5.megabytes
errors.add(:file_size, "file size must be less than 5 megabytes.")
end
end
Upvotes: 1
Reputation: 674
Try the following code.
validate :image_present
def image_present
if image.present? && image_file_size < 2.megabytes
errors.add(:file_size, "file size must be between 0 and 2 megabytes.")
end
end
Here, the validation will work if there is image present in the model and will skip the validation if there is no image.
Upvotes: 0