5

I am reading the book 'agile web development with rails' and I am at the part where they are going through validations, listed below:

class Product < ActiveRecord::Base
  validates :description, :title, :image_url, presence: true
  validates :price, numericality: {greater_than_or_equal_to: 0.01}
  validates :title, uniqueness: true
  validates :image_url, allow_blank: true, format: {
    with: %r{\.(gif|jpg|png)\z}i,
    message: 'Must include an image file extension'
  }
end

Something I am not understanding is that we have image_url, allow_blank set to true, but then we have to verify that the image_url is present? This seems like a contradiction to me at first glance, but I'm sure it's from lack of understanding.

What is it that the allow_blank validation is doing? And why do we not validate the :price be present also?

adamscott
  • 823
  • 1
  • 10
  • 31
  • http://stackoverflow.com/questions/14488465/understanding-rails-validation-what-does-allow-blank-do In short, it has to do with the uniqueness constraint – Yifei W Apr 21 '16 at 03:07
  • There is no uniqueness constraint on image url. The regex is making sure the image url is `.gif`, `.jpg`, or `.png`format. The `allow_blank` tells rails that the field can either be blank or a image string in the valid format. If allow blank wasn't passed, all blank image url fields would fail as they don't meet the regex format. – miler350 Apr 21 '16 at 03:55

1 Answers1

11

I can see why you are confused about this---it is not very clear! The meaning of allow_blank: true is that if image_url is blank, then the format validator will not run. The presence validator will still run, because its declaration has no allow_blank option.

The reason the book is doing it this way is to avoid showing users 2 validation messages if they leave the field blank. You don't really want users to see "Image Url can't be blank; Image Url must include an image file extension". It's better to just show a message about it being blank. In other words, we only want to run the format validator if there is something to validate.

Paul A Jungwirth
  • 23,504
  • 14
  • 74
  • 93