简体   繁体   中英

rails validations allow_blank and presence

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM