There??™s more to it, but right now this will get
you started.
Validations
Normally the values that can be accepted on an attribute are constrained in one or several
ways that won??™t show up in the database schema. For example, a price for a Product shouldn??™t
be negative. These model constraints exist in the model class, and you??™ll add a few to show
how Rails validations typically look. Validations are important, because they stop invalid data
from entering the database.
The first model is ProductType. There??™s only one invariant, and that is that there should
always be a name for it. (Rails automatically caters for the id field, so you won??™t have to ensure
that it exists.) Validating the presence of an attribute, where presence means it should be there,
and not be empty, is easy. You just add the validates_presence_of method to the model class.
After adding that, the file app/models/product_type.rb looks like this:
class ProductType < ActiveRecord::Base
has_many :products
validates_presence_of :name
end
You??™ll also add a few validations to the Product model. First, there are a few required
attributes. These are price, name, and product_type. A Product isn??™t valid without this information.
On the other hand, a Product doesn??™t need a description. So, you add the validation to the
app/models/product.rb file:
validates_presence_of :price, :name, :product_type
The next part is price. Because you represent price as cents, it should be an integer, and
nothing else.
Pages:
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120