1 #---
2 # Excerpted from "Agile Web Development with Rails, 3rd Ed.",
3 # published by The Pragmatic Bookshelf.
4 # Copyrights apply to this code. It may not be used to create training material,
5 # courses, books, articles, and the like. Contact us if you are in doubt.
6 # We make no guarantees that this code is fit for any purpose.
7 # Visit http://www.pragmaticprogrammer.com/titles/rails3 for more book information.
8 #---
9
10
11 class Product < ActiveRecord::Base
12 has_many :orders, :through => :line_items
13 has_many :line_items
14 # ...
15
16
17 def self.find_products_for_sale
18 find(:all, :order => "title")
19 end
20
21 # validation stuff...
22
23
24
25
26
27 validates_presence_of :title, :description, :image_url
28
29
30 validates_numericality_of :price
31
32
33 validate :price_must_be_at_least_a_cent
34
35
36 validates_uniqueness_of :title
37
38
39 validates_format_of :image_url,
40 :with => %r{\.(gif|jpg|png)$}i,
41 :message => 'must be a URL for GIF, JPG ' +
42 'or PNG image.'
43
44
45
46 protected
47 def price_must_be_at_least_a_cent
48 errors.add(:price, 'should be at least 0.01') if price.nil? ||
49 price < 0.01
50 end
51
52
53
54 end