aboutsummaryrefslogblamecommitdiffstats
path: root/railties/guides/source/activerecord_validations_callbacks.textile
blob: 28948eca7766e165f86f0463abb158cb78eb7fab (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
h2. Active Record Validations and Callbacks

This guide teaches you how to hook into 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 as well as how to perform custom operations at certain points in the object lifecycle.

After reading this guide and trying out the presented concepts, we hope that you'll be able to:

* Use the built-in Active Record validation helpers
* Create your own custom validation methods
* Work with the error messages generated by the validation process
* Create callback methods to respond to events in the object lifecycle.
* Create special classes that encapsulate common behavior for your callbacks
* Create Rails Observers

endprologue.

# TODO consider starting with an overview of what validations and callbacks are, and the object lifecycle
# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
# http://api.rubyonrails.org/classes/ActiveRecord/Base.html

h3. Overview of ActiveRecord Validation

Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture. Why should you use validations? When do these validations take place?

h4. Why Use ActiveRecord Validations?

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.

There are several ways that you could validate the data that goes to the database, including native database constraints, client-side validations, and model-level validations. Each of these has pros and cons:

* Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and maintain 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. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that are problematic to implement from the application level.
* Implementing validations only at the client side can be difficult in 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.
* Using validation directly in 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 ability to easily create validations, providing built-in helpers for common validations while still allowing you to create your own validation methods.

# TODO consider adding a bullet point on validations in controllers, and why model validations should be preferred over complicated controllers.
# http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model

h4. When Does Validation Happen?

There are two kinds of Active Record objects: those that correspond to a row inside your database and those that 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 will be saved into the appropriate database table. Active Record uses the +new_record?+ instance method to determine whether an object is already in the database or not. Consider the following simple Active Record class:

<ruby>
class Person < ActiveRecord::Base
end
</ruby>

We can see how it works by looking at some script/console output:

<shell>
>> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
=> #<Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil>
>> p.new_record?
=> true
>> p.save
=> true
>> p.new_record?
=> false
</shell>

Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not trigger the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an object in the database that's invalid. You can choose to have specific validations run when an object is created, saved, or updated.

CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.

The following methods trigger validations, and will save the object to the database only if the object is valid. The bang versions (e.g. +save!+) will raise an exception if the record is invalid. The non-bang versions (e.g. +save+) simply return +false+.

* +create+
* +create!+
* +save+
* +save!+
* +update+
* +update_attributes+
* +update_attributes!+

h4. Skipping Validations

The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.

* +decrement!+
* +decrement_counter+
* +increment!+
* +increment_counter+
* +toggle!+
* +update_all+
* +update_attribute+
* +update_counters+

Note that +save+ also has the ability to skip validations (and callbacks!) if passed +false+. This technique should be used with caution.

* +save(false)+

h4. Object#valid? and Object#invalid?

To verify whether or not an object is valid, you can use the +valid?+ method. This runs validations and returns true if no errors were added to the object, and false otherwise.

<ruby>
class Person < ActiveRecord::Base
  validates_presence_of :name
end

Person.create(:name => "John Doe").valid? # => true
Person.create.valid? # => false
</ruby>

When Active Record is performing validations, any errors found are collected into an +errors+ instance variable and can be accessed through an +errors+ instance method. An object is considered invalid if it has errors, and calling +save+ or +save!+ will not save it to the database.

However, note that an object instantiated with +new+ will not report errors even if it's technically invalid, because validations are not run when using +new+.

<ruby>
class Person < ActiveRecord::Base
  validates_presence_of :name
end

>> p = Person.new
=> #<Person id: nil, name: nil>
>> p.errors
=> #<ActiveRecord::Errors:0x3b8b46c @base=#<Person id: nil, name: nil>, @errors={}>
>> p.valid?
=> false
>> p.errors
=> #<ActiveRecord::Errors:0x3b8b46c @base=#<Person id: nil, name: nil>, @errors={"name"=>["can't be blank"]}>
>> p = Person.create
=> #<Person id: nil, name: nil>
>> p.errors
=> #<ActiveRecord::Errors:0x3b8b46c @base=#<Person id: nil, name: nil>, @errors={"name"=>["can't be blank"]}>
>> p.save
=> false
>> p.save!
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
>> p = Person.create!
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
</ruby>

To verify whether or not a particular attribute of an object is valid, you can use the +invalid?+ method. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +valid?+ method because it doesn't verify the validity of the object as a whole, but only if there are errors found on an individual attribute of the object.

<ruby>
class Person < ActiveRecord::Base
  validates_presence_of :name
end

>> Person.new.errors.invalid?(:name) # => false
>> Person.create.errors.invalid?(:name) # => true
</ruby>

h3. Declarative Validation Helpers

Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validation rules that are commonly used. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated.

Each helper accepts an arbitrary number of attributes identified by symbols, so with a single line of code you can add the same kind of validation to several attributes.

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 of the values +:save+ (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.

h4. validates_acceptance_of

Validates that a checkbox on the user interface was checked when a form was submitted. This is normally used when the user needs to agree to your application's terms of service, confirm reading some text, 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).

<ruby>
class Person < ActiveRecord::Base
  validates_acceptance_of :terms_of_service
end
</ruby>

The default error message for +validates_acceptance_of+ is "_must be accepted_"

+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 this.

<ruby>
class Person < ActiveRecord::Base
  validates_acceptance_of :terms_of_service, :accept => 'yes'
end
</ruby>

h4. validates_associated

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.

<ruby>
class Library < ActiveRecord::Base
  has_many :books
  validates_associated :books
end
</ruby>

This validation will work with all the association types.

CAUTION: Don't use +validates_associated+ on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.

The default error message for +validates_associated+ is "_is invalid_". Note that each associated object will contain its own +errors+ collection; errors do not bubble up to the calling model.

h4. validates_confirmation_of

You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with '_confirmation' appended.

<ruby>
class Person < ActiveRecord::Base
  validates_confirmation_of :email
end
</ruby>

In your view template you could use something like

<erb>
<%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %>
</erb>

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):

<ruby>
class Person < ActiveRecord::Base
  validates_confirmation_of :email
  validates_presence_of :email_confirmation
end
</ruby>

The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_"

h4. validates_exclusion_of

This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.

<ruby>
class MovieFile < ActiveRecord::Base
  validates_exclusion_of :format, :in => %w(mov avi),
    :message => "Extension %s is not allowed"
end
</ruby>

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. This example uses the +:message+ option to show how you can personalize it with the current attribute's value, through the +%s+ format mask.

The default error message for +validates_exclusion_of+  is "_is not included in the list_".

h4. validates_format_of

This helper validates the attributes' values by testing whether they match a given pattern. This pattern must be specified using a Ruby regular expression, which is specified using the +:with+ option.

<ruby>
class Product < ActiveRecord::Base
  validates_format_of :description, :with => /^[a-zA-Z]+$/,
    :message => "Only letters allowed"
end
</ruby>

The default error message for +validates_format_of+ is "_is invalid_".

h4. validates_inclusion_of

This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.

<ruby>
class Coffee < ActiveRecord::Base
  validates_inclusion_of :size, :in => %w(small medium large),
    :message => "%s is not a valid size"
end
</ruby>

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. The previous example uses the +:message+ option to show how you can personalize it with the current attribute's value, through the +%s+ format mask.

The default error message for +validates_inclusion_of+  is "_is not included in the list_".

h4. validates_length_of

This helper validates the length of your attribute's value. It includes a variety of different options, so you can specify length constraints in different ways:

<ruby>
class Person < ActiveRecord::Base
  validates_length_of :name, :minimum => 2
  validates_length_of :bio, :maximum => 500
  validates_length_of :password, :in => 6..20
  validates_length_of :registration_number, :is => 6
end
</ruby>

The possible length constraint options are:

* +:minimum+ - The attribute cannot have less than the specified length.
* +:maximum+ - The attribute cannot have more than the specified length.
* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
* +:is+ - The attribute length must be equal to a given value.

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 constraint being used. You can still use the +:message+ option to specify an error message.

<ruby>
class Person < ActiveRecord::Base
  validates_length_of :bio, :too_long => "you're writing too much. %d characters is the maximum allowed."
end
</ruby>

The +validates_size_of+ helper is an alias for +validates_length_of+.

h4. validates_numericality_of

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.

If you set +:integer_only+ 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 to a number using +Kernel.Float+.

<ruby>
class Player < ActiveRecord::Base
  validates_numericality_of :points
  validates_numericality_of :games_played, :only_integer => true
end
</ruby>

Besides +:only_integer+, the +validates_numericality_of+ helper also accepts the following options to add constraints to acceptable values:

* +:greater_than+ - Specifies the value must be greater than the supplied value. The default error message for this option is "_must be greater than (value)_"
* +:greater_than_or_equal_to+ - Specifies the value must be greater than or equal the supplied value. The default error message for this option is "_must be greater than or equal to (value)_"
* +:equal_to+ - Specifies the value must be equal to the supplied value. The default error message for this option is "_must be equal to (value)_"
* +:less_than+ - Specifies the value must be less than the supplied value. The default error message for this option is "_must e less than (value)_"
* +:less_than_or_equal_to+ - Specifies the value must be less than or equal the supplied value. The default error message for this option is "_must be less or equal to (value)_"
* +:odd+ - Specifies the value must be an odd number if set to true. The default error message for this option is "_must be odd_"
* +:even+ - Specifies the value must be an even number if set to true. The default error message for this option is "_must be even_"


The default error message for +validates_numericality_of+ is "_is not a number_".

h4. validates_presence_of

This helper validates that the specified 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).

<ruby>
class Person < ActiveRecord::Base
  validates_presence_of :name, :login, :email
end
</ruby>

NOTE: If you want to be sure that an association is present, you'll need to test whether the foreign key used to map the association is present, and not the associated object itself.

<ruby>
class LineItem < ActiveRecord::Base
  belongs_to :order
  validates_presence_of :order_id
end
</ruby>

NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you should use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true

The default error message for +validates_presence_of+ is "_can't be empty_".

h4. validates_uniqueness_of

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 intend to be unique. To avoid that, you must create an unique index in your database.

<ruby>
class Account < ActiveRecord::Base
  validates_uniqueness_of :email
end
</ruby>

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.

There is a +:scope+ option that you can use to specify other attributes that are used to limit the uniqueness check:

<ruby>
class Holiday < ActiveRecord::Base
  validates_uniqueness_of :name, :scope => :year,
    :message => "Should happen once per year"
end
</ruby>

There is also a +:case_sensitive+ option that you can use to define whether the uniqueness constraint will be case sensitive or not. This option defaults to true.

<ruby>
class Person < ActiveRecord::Base
  validates_uniqueness_of :name, :case_sensitive => false
end
</ruby>

The default error message for +validates_uniqueness_of+ is "_has already been taken_".

h4. validates_each

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.

<ruby>
class Person < ActiveRecord::Base
  validates_each :name, :surname do |model, attr, value|
    model.errors.add(attr, 'Must start with upper case') if value =~ /^[a-z]/
  end
end
</ruby>

The block receives the model, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you can add an error message to the model, therefore making it invalid.

h3. Common Validation Options

There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which are discussed later in the conditional validation topic.

h4. :allow_nil

The +:allow_nil+ option skips the validation when the value being validated is +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, the validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+.

<ruby>
class Coffee < ActiveRecord::Base
  validates_inclusion_of :size, :in => %w(small medium large),
    :message => "%s is not a valid size", :allow_nil => true
end
</ruby>

h4. :allow_blank

The +:allow_blank+ option is similar to the +:allow_nil+ option. This option will let validation pass if the attribute's value is +nil+ or an empty string, i.e., any value that returns +true+ for +blank?+.

<ruby>
class Topic < ActiveRecord::Base
  validates_length_of :title, :is => 5, :allow_blank => true
end

Topic.create("title" => "").valid? # => true
Topic.create("title" => nil).valid? # => true
</ruby>

h4. :message

As you've already seen, 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, together with the attribute name.

h4. :on

The +:on+ option lets you specify when the validation should happen. The default behavior 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.

<ruby>
class Person < ActiveRecord::Base
  # => it will be possible to update email with a duplicated value
  validates_uniqueness_of :email, :on => :create

  # => it will be possible to create the record with a 'non-numerical age'
  validates_numericality_of :age, :on => :update

  # => the default (validates on both create and update)
  validates_presence_of :name, :on => :save
end
</ruby>

h3. Conditional validation

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.

h4. Using a symbol with :if and :unless

You can associate 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.

<ruby>
class Order < ActiveRecord::Base
  validates_presence_of :card_number, :if => :paid_with_card?

  def paid_with_card?
    payment_type == "card"
  end
end
</ruby>

h4. Using a string with the :if and :unless

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.

<ruby>
class Person < ActiveRecord::Base
  validates_presence_of :surname, :if => "name.nil?"
end
</ruby>

h4. Using a Proc object with :if and :unless

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 ability 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.

<ruby>
class Account < ActiveRecord::Base
  validates_confirmation_of :password,
    :unless => Proc.new { |a| a.password.blank? }
end
</ruby>

h3. Writing your own validation methods

When the built-in validation helpers are not enough for your needs, you can write your own validation methods. You can do that by implementing methods that verify the state of your models and add messages to their +errors+ collection when they are invalid. You must then register those methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names. You can pass more than one symbol for each class method and the respective validations will be ran in the same order as they were registered.

<ruby>
class Invoice < ActiveRecord::Base
  validate :expiration_date_cannot_be_in_the_past,
    :discount_cannot_be_more_than_total_value

  def expiration_date_cannot_be_in_the_past
    errors.add(:expiration_date, "can't be in the past") if
      !expiration_date.blank? and expiration_date < Date.today
  end

  def discount_cannot_be_greater_than_total_value
    errors.add(:discount, "can't be greater than total value") unless
      discount <= total_value
  end
end
</ruby>

You can even create your own validation helpers and reuse them in several different models. Here is an example where we create a custom validation helper to validate the format of fields that represent email addresses:

<ruby>
module ActiveRecord
  module Validations
    module ClassMethods
      def validates_email_format_of(value)
        validates_format_of value,
          :with => /\A[\w\._%-]+@[\w\.-]+\.[a-zA-Z]{2,4}\z/,
          :if => Proc.new { |u| !u.email.blank? },
          :message => "Invalid format for email address"
      end
    end
  end
end
</ruby>

The recipe is simple: just create a new validation method inside the +ActiveRecord::Validations::ClassMethods+ module. You can put this code in a file inside your application's *lib* folder, and then requiring it from your *environment.rb* or any other file inside *config/initializers*. You can use this helper like this:

<ruby>
class Person < ActiveRecord::Base
  validates_email_format_of :email_address
end
</ruby>

h3. Manipulating the errors collection

# TODO consider renaming section to something more simple, like "Validation errors"
# Consider combining with new section at the top with Object#valid? and Object#invalid?
# Consider moving this stuff above the current 2-6 sections (e.g. save the validation details until after this?)

You can do more than just call +valid?+ upon your objects based on the existence of the +errors+ collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object's state.

* +add_to_base+ lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of it's attributes. +add_to_base+ receives a string with the message.

<ruby>
class Person < ActiveRecord::Base
  def a_method_used_for_validation_purposes
    errors.add_to_base("This person is invalid because ...")
  end
end
</ruby>

* +add+ lets you manually add messages that are related to particular attributes. When writing those messages, keep in mind that Rails will prepend them with the name of the attribute that holds the error, so write it in a way that makes sense. +add+ receives a symbol with the name of the attribute that you want to add the message to and the message itself.

<ruby>
class Person < ActiveRecord::Base
  def a_method_used_for_validation_purposes
    errors.add(:name, "can't have the characters !@#$%*()_-+=")
  end
end
</ruby>

* +invalid?+ is used when you want to check if a particular attribute is invalid. It receives a symbol with the name of the attribute that you want to check.

<ruby>
class Person < ActiveRecord::Base
  validates_presence_of :name, :email
end

person = Person.new(:name => "John Doe")
person.errors.invalid?(:email) # => true
</ruby>

* +on+ is used when you want to check the error messages for a specific attribute. It will return different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute, +on+ will return +nil+. If there is just one errors message for this attribute, +on+ will return a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ will return an array of strings, each one with one error message.

<ruby>
class Person < ActiveRecord::Base
  validates_presence_of :name
  validates_length_of :name, :minimum => 3
end

person = Person.new(:name => "John Doe")
person.valid? # => true
person.errors.on(:name) # => nil

person = Person.new(:name => "JD")
person.valid? # => false
person.errors.on(:name)
# => "is too short (minimum is 3 characters)"

person = Person.new
person.valid? # => false
person.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
</ruby>

* +clear+ is used when you intentionally want to clear all the messages in the +errors+ collection. However, calling +errors.clear+ upon an invalid object won't make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run. If any of them fails, the +errors+ collection will get filled again.

<ruby>
class Person < ActiveRecord::Base
  validates_presence_of :name
  validates_length_of :name, :minimum => 3
end

person = Person.new
person.valid? # => false
person.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]

person.errors.clear
person.errors.empty? # => true
p.save # => false
p.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
</ruby>

# TODO consider discussing other methods (e.g. errors.size)
# http://api.rubyonrails.org/classes/ActiveRecord/Errors.html

h3. Using error collection in views

Rails provides built-in helpers to display the error messages of your models in your view templates. When creating a form with the form_for helper, you can use the error_messages method on the form builder to render all failed validation messages for the current model instance.

<ruby>
class Product < ActiveRecord::Base
  validates_presence_of :description, :value
  validates_numericality_of :value, :allow_nil => true
end
</ruby>

<erb>
<% form_for(@product) do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :description %><br />
    <%= f.text_field :description %>
  </p>
  <p>
    <%= f.label :value %><br />
    <%= f.text_field :value %>
  </p>
  <p>
    <%= f.submit "Create" %>
  </p>
<% end %>
</erb>

!images/error_messages.png(Error messages)!

You can also use the +error_messages_for+ helper to display the error messages of a model assigned to a view template. It's very similar to the previous example and will achieve exactly the same result.

<erb>
<%= error_messages_for :product %>
</erb>

The displayed text for each error message will always be formed by the capitalized name of the attribute that holds the error, followed by the error message itself.

Both the +form.error_messages+ and the +error_messages_for+ helpers accept options that let you customize the +div+ element that holds the messages, changing the header text, the message below the header text and the tag used for the element that defines the header.

<erb>
<%= f.error_messages :header_message => "Invalid product!",
  :message => "You'll need to fix the following fields:",
  :header_tag => :h3 %>
</erb>

Which results in the following content

!images/customized_error_messages.png(Customized error messages)!

If you pass +nil+ to any of these options, it will get rid of the respective section of the +div+.

It's also possible to change the CSS classes used by the +error_messages+ helper. These classes are automatically defined at the *scaffold.css* file, generated by the scaffold script. If you're not using scaffolding, you can still define those CSS classes at your CSS files. Here is a list of the default CSS classes.

* +.fieldWithErrors+ - Style for the form fields with errors.
* +#errorExplanation+ - Style for the +div+ element with the error messages.
* +#errorExplanation h2+ - Style for the header of the +div+ element.
* +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element.
* +#errorExplanation ul li+ - Style for the list of error messages.

h4. Changing the way form fields with errors are displayed

By default, form fields with errors are displayed enclosed by a +div+ element with the +fieldWithErrors+ CSS class. However, we can write some Ruby code to override the way Rails treats those fields by default. Here is a simple example where we change the Rails behaviour to always display the error messages in front of each of the form fields with errors. The error messages will be enclosed by a +span+ element with a +validation-error+ CSS class. There will be no +div+ element enclosing the +input+ element, so we get rid of that red border around the text field. You can use the +validation-error+ CSS class to style it anyway you want.

<ruby>
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  if instance.error_message.kind_of?(Array)
    %(#{html_tag}<span class='validation-error'>&nbsp;
      #{instance.error_message.join(',')}</span>)
  else
    %(#{html_tag}<span class='validation-error'>&nbsp;
      #{instance.error_message}</span>)
  end
end
</ruby>

This will result in something like the following content:

!images/validation_error_messages.png(Validation error messages)!

The way form fields with errors are treated is defined by the +ActionView::Base.field_error_proc+ Ruby Proc. This Proc receives two parameters:

* A string with the HTML tag
* An object of the +ActionView::Helpers::InstanceTag+ class.

h3. Callbacks

Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database.

# TODO discuss what does/doesn't trigger callbacks, like we did in the validations section (e.g. destroy versus delete).
# Consider moving up to the (new) intro overview section, before getting into details.
# http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002220
# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

h4. Callback registration

In order to use the available callbacks, you need to register them. You can do that by implementing them as an ordinary methods, and then using a macro-style class method to register then as callbacks.

<ruby>
class User < ActiveRecord::Base
  validates_presence_of :login, :email

  before_validation :ensure_login_has_a_value

  protected
  def ensure_login_has_a_value
    if self.login.nil?
      self.login = email unless email.blank?
    end
  end
end
</ruby>

The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line.

<ruby>
class User < ActiveRecord::Base
  validates_presence_of :login, :email

  before_create {|user| user.name = user.login.capitalize if user.name.blank?}
end
</ruby>

CAUTION: Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details.

# TODO consider not making this a warning, just a note (this is an implementation detail, not a requirement of the library)

h3. Conditional callbacks

Like in validations, we can also make our callbacks conditional, calling then only 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 callback *should* get called. If you want to specify when the callback *should not* be called, then you may use the +:unless+ option.

h4. Using a symbol with the :if and :unless

You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before the callback. If this method returns +false+ the callback won't be executed. This is the most common option. Using this form of registration it's also possible to register several different methods that should be called to check the if the callback should be executed.

<ruby>
class Order < ActiveRecord::Base
  before_save :normalize_card_number, :if => :paid_with_card?
end
</ruby>

h4. Using a string with the :if and :unless

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.

<ruby>
class Order < ActiveRecord::Base
  before_save :normalize_card_number, :if => "paid_with_card?"
end
</ruby>

h4. Using a Proc object with the :if and :unless

Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object. This option is best suited when writing short validation methods, usually one-liners.

<ruby>
class Order < ActiveRecord::Base
  before_save :normalize_card_number,
    :if => Proc.new { |order| order.paid_with_card? }
end
</ruby>

h4. Multiple Conditions for Callbacks

When writing conditional callbacks, it's possible to mix both +:if+ and +:unless+ in the same callback declaration.

<ruby>
class Comment < ActiveRecord::Base
  after_create :send_email_to_author, :if => :author_wants_emails?,
    :unless => Proc.new { |comment| comment.post.ignore_comments? }
end
</ruby>

h3. Available callbacks

# TODO consider moving above the code examples and details, possibly combining with intro lifecycle stuff?

Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations.

h4. Callbacks called both when creating or updating a record.

# TODO consider just listing these in the possible lifecycle of an object, roughly as they do here:
# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

* +before_validation+
* +after_validation+
* +before_save+
* *INSERT OR UPDATE OPERATION*
* +after_save+

h4. Callbacks called only when creating a new record.

* +before_validation_on_create+
* +after_validation_on_create+
* +before_create+
* *INSERT OPERATION*
* +after_create+

h4. Callbacks called only when updating an existing record.

* +before_validation_on_update+
* +after_validation_on_update+
* +before_update+
* *UPDATE OPERATION*
* +after_update+

h4. Callbacks called when removing a record from the database.

* +before_destroy+
* *DELETE OPERATION*
* +after_destroy+

The +before_destroy+ and +after_destroy+ callbacks will only be called if you delete the model using either the +destroy+ instance method or one of the +destroy+ or +destroy_all+ class methods of your Active Record class. If you use +delete+ or +delete_all+ no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database.

h4. after_initialize and after_find callbacks

The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by directly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method.

The +after_find+ callback will be called whenever Active Record loads a record from the database. When used together with +after_initialize+ it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.

The +after_initialize+ and +after_find+ callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries.

h3. Halting Execution

As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the +before_create+, +before_save+, +before_update+ or +before_destroy+ callback methods returns a boolean +false+ (not +nil+) value or raise and exception, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on. It's because the whole callback chain is wrapped in a transaction, so raising an exception or returning +false+ fires a database ROLLBACK.

h3. Callback classes

Sometimes the callback methods that you'll write will be useful enough to be reused at other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.

Here's an example where we create a class with a after_destroy callback for a PictureFile model.

<ruby>
class PictureFileCallbacks
  def after_destroy(picture_file)
    File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
  end
end
</ruby>

When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:

<ruby>
class PictureFile < ActiveRecord::Base
  after_destroy PictureFileCallbacks.new
end
</ruby>

Note that we needed to instantiate a new PictureFileCallbacks object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method.

<ruby>
class PictureFileCallbacks
  def self.after_destroy(picture_file)
    File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
  end
end
</ruby>

If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object.

<ruby>
class PictureFile < ActiveRecord::Base
  after_destroy PictureFileCallbacks
end
</ruby>

You can declare as many callbacks as you want inside your callback classes.

h3. Observers

Active Record callbacks are a powerful feature, but they can pollute your model implementation with code that's not directly related to the model's purpose. In object-oriented software, it's always a good idea to design your classes with a single responsibility in the whole system. For example, it wouldn't make much sense to have a +User+ model with a method that writes data about a login attempt to a log file. Whenever you're using callbacks to write code that's not directly related to your model class purposes, it may be a good moment to create an Observer.

An Active Record Observer is an object that links itself to a model and registers its methods for callbacks. Your model's implementation remains clean, while you can reuse the code in the Observer to add behaviour to more than one model class. OK, you may say that we can also do that using callback classes, but it would still force us to add code to our model's implementation.

Observer classes are subclasses of the ActiveRecord::Observer class. When this class is subclassed, Active Record will look at the name of the new class and then strip the 'Observer' part to find the name of the Active Record class to observe.

Consider a Registration model, where we want to send an email every time a new registration is created. Since sending emails is not directly related to our model's purpose, we could create an Observer to do just that:

<ruby>
class RegistrationObserver < ActiveRecord::Observer
  def after_create(model)
    # code to send registration confirmation emails...
  end
end
</ruby>

Like in callback classes, the observer's methods receive the observed model as a parameter.

Sometimes using the ModelName + Observer naming convention won't be the best choice, mainly when you want to use the same observer for more than one model class. It's possible to explicity specify the models that our observer should observe.

<ruby>
class Auditor < ActiveRecord::Observer
  observe User, Registration, Invoice
end
</ruby>

h4. Registering observers

If you paid attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiated and begin to interact with our models. For observers to work we need to register them somewhere. The usual place to do that is in our application's *config/environment.rb* file. In this file there is a commented-out line where we can define the observers that our application should load at start-up.

<ruby>
# Activate observers that should always be running
config.active_record.observers = :registration_observer, :auditor
</ruby>

You can uncomment the line with +config.active_record.observers+ and change the symbols for the name of the observers that should be registered.

It's also possible to register callbacks in any of the files living at *config/environments/*, if you want an observer to work only in a specific environment. There is not a +config.active_record.observers+ line at any of those files, but you can simply add it.

h4. Where to put the observers' source files

By convention, you should always save your observers' source files inside *app/models*.

# TODO this probably doesn't need it's own section and entry in the table of contents.

h3. Changelog

"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks

January 9, 2009: Initial version by "Cássio Marques":credits.html#cmarques