The Depot Application

The Depot Application

6.5 Iteration A4: Making Prettier Listings 6.3 Iteration A2: Add a Missing Column

6.4 Iteration A3: Validate!

edit app/models/product.rb
class Product < ActiveRecord::Base
  validates_presence_of :title, :description, :image_url
  validates_numericality_of :price
  validate :price_must_be_at_least_a_cent
  validates_uniqueness_of :title
  validates_format_of :image_url, :allow_blank => true,
                      :with    => %r{\.(gif|jpg|png)$}i,
                      :message => 'must be a URL for GIF, JPG ' +
                                  'or PNG image.'
 
protected
  def price_must_be_at_least_a_cent
    errors.add(:price, 'should be at least 0.01') if price.nil? ||
                       price < 0.00
  end
 
end
get /products/new

New product





Back
post /products

New product

3 errors prohibited this product from being saved:

  • Title can't be blank
  • Description can't be blank
  • Image url can't be blank




Back
get /products/new

New product





Back
post /products

New product

1 error prohibited this product from being saved:

  • Price is not a number




Back
edit app/models/product.rb
class Product < ActiveRecord::Base
  validates_presence_of :title, :description, :image_url
  validates_numericality_of :price
  validate :price_must_be_at_least_a_cent
  validates_uniqueness_of :title
  validates_format_of :image_url,
                      :with    => %r{\.(gif|jpg|png)$}i,
                      :message => 'must be a URL for GIF, JPG ' +
                                  'or PNG image.'
 
protected
  def price_must_be_at_least_a_cent
    errors.add(:price, 'should be at least 0.01') if price.nil? ||
                       price < 0.01
  end
 
end

6.5 Iteration A4: Making Prettier Listings 6.3 Iteration A2: Add a Missing Column