Finished Chapter 12
[depot.git] / app / models / product.rb
1 class Product < ActiveRecord::Base
2 has_many :line_items
3 has_many :orders, :through => :line_items
4
5 validates_presence_of :title, :description, :image_url
6 validates_numericality_of :price
7 validate :price_must_be_at_least_a_penny
8 validates_uniqueness_of :title
9 validates_format_of :image_url,
10 :with => %r{\.(gif|jpg|png)$}i,
11 :message => "must be a URL for GIF, JPG, or PNG image."
12
13 def self.find_products_for_sale
14 find(:all,
15 :conditions => "date_available <= now() and (date_available_until is null or date_available_until >= now())",
16 :order => :title)
17 end
18
19 protected
20 def price_must_be_at_least_a_penny
21 errors.add(:price, 'should be at least 0.01') if price.nil? || price < 0.01
22 end
23 end