Froze rails gems
[depot.git] / vendor / rails / railties / doc / guides / source / activerecord_validations_callbacks.txt
1 Active Record Validations and Callbacks
2 =======================================
3
4 This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles.
5
6 After reading this guide and trying out the presented concepts, we hope that you'll be able to:
7
8 * Correctly use all the built-in Active Record validation helpers
9 * Create your own custom validation methods
10 * Work with the error messages generated by the validation proccess
11 * Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved.
12 * Create special classes that encapsulate common behaviour for your callbacks
13 * Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
14
15 == Motivations to validate your Active Record objects
16
17 The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.
18
19 There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons:
20
21 * Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level.
22 * Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
23 * Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods.
24
25 == How it works
26
27 === When does validation happens?
28
29 There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it'll be recorded to it's table. Active Record uses the +new_record?+ instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class:
30
31 [source, ruby]
32 ------------------------------------------------------------------
33 class Person < ActiveRecord::Base
34 end
35 ------------------------------------------------------------------
36
37 We can see how it works by looking at the following script/console output:
38
39 ------------------------------------------------------------------
40 >> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
41 => #<Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil>
42 >> p.new_record?
43 => true
44 >> p.save
45 => true
46 >> p.new_record?
47 => false
48 ------------------------------------------------------------------
49
50 Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+, +update_attribute+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
51
52 === The meaning of 'valid'
53
54 For verifying if an object is valid, Active Record uses the +valid?+ method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the +errors+ instance method. The proccess is really simple: If the +errors+ method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the +errors+ collection.
55
56 == The declarative validation helpers
57
58 Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's +errors+ collection, this message being associated with the field being validated.
59
60 Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.
61
62 All these helpers accept the +:on+ and +:message+ options, which define when the validation should be applied and what message should be added to the +errors+ collection when it fails, respectively. The +:on+ option takes one the values +:save+ (it's the default), +:create+ or +:update+. There is a default error message for each one of the validation helpers. These messages are used when the +:message+ option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order.
63
64 === The +validates_acceptance_of+ helper
65
66 Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this 'acceptance' does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).
67
68 [source, ruby]
69 ------------------------------------------------------------------
70 class Person < ActiveRecord::Base
71 validates_acceptance_of :terms_of_service
72 end
73 ------------------------------------------------------------------
74
75 The default error message for +validates_acceptance_of+ is "_must be accepted_"
76
77 +validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.
78
79 [source, ruby]
80 ------------------------------------------------------------------
81 class Person < ActiveRecord::Base
82 validates_acceptance_of :terms_of_service, :accept => 'yes'
83 end
84 ------------------------------------------------------------------
85
86
87 === The +validates_associated+ helper
88
89 You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, +valid?+ will be called upon each one of the associated objects.
90
91 [source, ruby]
92 ------------------------------------------------------------------
93 class Library < ActiveRecord::Base
94 has_many :books
95 validates_associated :books
96 end
97 ------------------------------------------------------------------
98
99 This validation will work with all the association types.
100
101 CAUTION: Pay attention not to use +validates_associated+ on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.
102
103 The default error message for +validates_associated+ is "_is invalid_". Note that the errors for each failed validation in the associated objects will be set there and not in this model.
104
105 === The +validates_confirmation_of+ helper
106
107 You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with '_confirmation' appended.
108
109 [source, ruby]
110 ------------------------------------------------------------------
111 class Person < ActiveRecord::Base
112 validates_confirmation_of :email
113 end
114 ------------------------------------------------------------------
115
116 In your view template you could use something like
117 ------------------------------------------------------------------
118 <%= text_field :person, :email %>
119 <%= text_field :person, :email_confirmation %>
120 ------------------------------------------------------------------
121
122 NOTE: This check is performed only if +email_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at +validates_presence_of+ later on this guide):
123
124 [source, ruby]
125 ------------------------------------------------------------------
126 class Person < ActiveRecord::Base
127 validates_confirmation_of :email
128 validates_presence_of :email_confirmation
129 end
130 ------------------------------------------------------------------
131
132 The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_"
133
134 === The +validates_each+ helper
135
136 This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to +validates_each+ will be tested against it. In the following example, we don't want names and surnames to begin with lower case.
137
138 [source, ruby]
139 ------------------------------------------------------------------
140 class Person < ActiveRecord::Base
141 validates_each :name, :surname do |model, attr, value|
142 model.errors.add(attr, 'Must start with upper case') if value =~ /^[a-z]/
143 end
144 end
145 ------------------------------------------------------------------
146
147 The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid.
148
149 === The +validates_exclusion_of+ helper
150
151 This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
152
153 [source, ruby]
154 ------------------------------------------------------------------
155 class MovieFile < ActiveRecord::Base
156 validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
157 end
158 ------------------------------------------------------------------
159
160 The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
161
162 The default error message for +validates_exclusion_of+ is "_is not included in the list_".
163
164 === The +validates_format_of+ helper
165
166 This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the +:with+ option.
167
168 [source, ruby]
169 ------------------------------------------------------------------
170 class Product < ActiveRecord::Base
171 validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
172 end
173 ------------------------------------------------------------------
174
175 The default error message for +validates_format_of+ is "_is invalid_".
176
177 === The +validates_inclusion_of+ helper
178
179 This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
180
181 [source, ruby]
182 ------------------------------------------------------------------
183 class Coffee < ActiveRecord::Base
184 validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
185 end
186 ------------------------------------------------------------------
187
188 The +validates_inclusion_of+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
189
190 The default error message for +validates_inclusion_of+ is "_is not included in the list_".
191
192 === The +validates_length_of+ helper
193
194 This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways.
195
196 [source, ruby]
197 ------------------------------------------------------------------
198 class Person < ActiveRecord::Base
199 validates_length_of :name, :minimum => 2
200 validates_length_of :bio, :maximum => 500
201 validates_length_of :password, :in => 6..20
202 validates_length_of :registration_number, :is => 6
203 end
204 ------------------------------------------------------------------
205
206 The possible length constraint options are:
207
208 * +:minimum+ - The attribute cannot have less than the specified length.
209 * +:maximum+ - The attribute cannot have more than the specified length.
210 * +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
211 * +:is+ - The attribute length must be equal to a given value.
212
213 The default error messages depend on the type of length validation being performed. You can personalize these messages, using the +:wrong_length+, +:too_long+ and +:too_short+ options and the +%d+ format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the +:message+ option to specify an error message.
214
215 [source, ruby]
216 ------------------------------------------------------------------
217 class Person < ActiveRecord::Base
218 validates_length_of :bio, :too_long => "you're writing too much. %d characters is the maximum allowed."
219 end
220 ------------------------------------------------------------------
221
222 This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to.
223
224 === The +validates_numericallity_of+ helper
225
226 This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed.
227
228 If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z/$$+ regular expression to validate the attribute's value. Otherwise, it will try to convert the value using +Kernel.Float+.
229
230 [source, ruby]
231 ------------------------------------------------------------------
232 class Player < ActiveRecord::Base
233 validates_numericallity_of :points
234 validates_numericallity_of :games_played, :integer_only => true
235 end
236 ------------------------------------------------------------------
237
238 The default error message for +validates_numericallity_of+ is "_is not a number_".
239
240 === The +validates_presence_of+ helper
241
242 This helper validates that the attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty).
243
244 [source, ruby]
245 ------------------------------------------------------------------
246 class Person < ActiveRecord::Base
247 validates_presence_of :name, :login, :email
248 end
249 ------------------------------------------------------------------
250
251 NOTE: If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself.
252
253 [source, ruby]
254 ------------------------------------------------------------------
255 class LineItem < ActiveRecord::Base
256 belongs_to :order
257 validates_presence_of :order_id
258 end
259 ------------------------------------------------------------------
260
261 NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true
262
263 The default error message for +validates_presence_of+ is "_can't be empty_".
264
265 === The +validates_uniqueness_of+ helper
266
267 This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.
268
269 [source, ruby]
270 ------------------------------------------------------------------
271 class Account < ActiveRecord::Base
272 validates_uniqueness_of :email
273 end
274 ------------------------------------------------------------------
275
276 The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.
277
278 There is a +:scope+ option that you can use to specify other attributes that must be used to define uniqueness:
279
280 [source, ruby]
281 ------------------------------------------------------------------
282 class Holiday < ActiveRecord::Base
283 validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
284 end
285 ------------------------------------------------------------------
286
287 There is also a +:case_sensitive+ option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.
288
289 [source, ruby]
290 ------------------------------------------------------------------
291 class Person < ActiveRecord::Base
292 validates_uniqueness_of :name, :case_sensitive => false
293 end
294 ------------------------------------------------------------------
295
296 The default error message for +validates_uniqueness_of+ is "_has already been taken_".
297
298 == Common validation options
299
300 There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which we'll cover right at the next topic.
301
302 === The +:allow_nil+ option
303
304 You may use the +:allow_nil+ option everytime you just want to trigger a validation if the value being validated is not +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+.
305
306 [source, ruby]
307 ------------------------------------------------------------------
308 class Coffee < ActiveRecord::Base
309 validates_inclusion_of :size, :in => %w(small medium large),
310 :message => "%s is not a valid size", :allow_nil => true
311 end
312 ------------------------------------------------------------------
313
314 === The +:message+ option
315
316 As stated before, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.
317
318 === The +:on+ option
319
320 As stated before, the +:on+ option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +:on =$$>$$ :create+ to run the validation only when a new record is created or +:on =$$>$$ :update+ to run the validation only when a record is updated.
321
322 [source, ruby]
323 ------------------------------------------------------------------
324 class Person < ActiveRecord::Base
325 validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
326 validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
327 validates_presence_of :name, :on => :save # => that's the default
328 end
329 ------------------------------------------------------------------
330
331 == Conditional validation
332
333 Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a Ruby Proc. You may use the +:if+ option when you want to specify when the validation *should* happen. If you want to specify when the validation *should not* happen, then you may use the +:unless+ option.
334
335 === Using a symbol with the +:if+ and +:unless+ options
336
337 You can associated the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
338
339 [source, ruby]
340 ------------------------------------------------------------------
341 class Order < ActiveRecord::Base
342 validates_presence_of :card_number, :if => :paid_with_card?
343
344 def paid_with_card?
345 payment_type == "card"
346 end
347 end
348 ------------------------------------------------------------------
349
350 === Using a string with the +:if+ and +:unless+ options
351
352 You can also use a string that will be evaluated using +:eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
353
354 [source, ruby]
355 ------------------------------------------------------------------
356 class Person < ActiveRecord::Base
357 validates_presence_of :surname, :if => "name.nil?"
358 end
359 ------------------------------------------------------------------
360
361 === Using a Proc object with the +:if+ and :+unless+ options
362
363 Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object which will be called. Using a Proc object can give you the hability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners.
364
365 [source, ruby]
366 ------------------------------------------------------------------
367 class Account < ActiveRecord::Base
368 validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
369 end
370 ------------------------------------------------------------------
371
372 == Writing your own validation methods
373
374 When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the +validate+, +validate_on_create+ or +validate_on_update+ methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's +errors+ collection.
375
376 [source, ruby]
377 ------------------------------------------------------------------
378 class Invoice < ActiveRecord::Base
379 def validate_on_create
380 errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
381 end
382 end
383 ------------------------------------------------------------------
384
385 If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names.
386
387 [source, ruby]
388 ------------------------------------------------------------------
389 class Invoice < ActiveRecord::Base
390 validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
391
392 def expiration_date_cannot_be_in_the_past
393 errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
394 end
395
396 def discount_cannot_be_greater_than_total_value
397 errors.add(:discount, "can't be greater than total value") unless discount <= total_value
398 end
399 end
400 ------------------------------------------------------------------
401
402 == Changelog
403
404 http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks