aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/html/activerecord_validations_callbacks.html
blob: be556283c14194156a48b768757cf037bc88066a (plain) (blame)
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Active Record Validations and Callbacks</title>
  <!--[if lt IE 8]>
  <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
  <![endif]-->
  <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
  <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
  <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
</head>
<body>
  <div id="header" >
    <div id="logo">
      <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
    </div>

    <h1 id="site_title"><span>Ruby on Rails</span></h1>
    <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>

    <ul id="navMain">
      <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
      <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
    </ul>
  </div>

  <div id="container">
    
    <div id="sidebar">
      <h2>Chapters</h2>
      <ol>
          <li>
          <a href="#_overview_of_activerecord_validation">Overview of ActiveRecord Validation</a>
            <ul>
            
              <li><a href="#_why_use_activerecord_validations">Why Use ActiveRecord Validations?</a></li>
            
              <li><a href="#_when_does_validation_happen">When Does Validation Happen?</a></li>
            
              <li><a href="#_the_meaning_of_tt_valid_tt">The Meaning of <tt>valid</tt></a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_the_declarative_validation_helpers">The Declarative Validation Helpers</a>
            <ul>
            
              <li><a href="#_the_tt_validates_acceptance_of_tt_helper">The <tt>validates_acceptance_of</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_associated_tt_helper">The <tt>validates_associated</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_confirmation_of_tt_helper">The <tt>validates_confirmation_of</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_exclusion_of_tt_helper">The <tt>validates_exclusion_of</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_format_of_tt_helper">The <tt>validates_format_of</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_inclusion_of_tt_helper">The <tt>validates_inclusion_of</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_length_of_tt_helper">The <tt>validates_length_of</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_numericality_of_tt_helper">The <tt>validates_numericality_of</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_presence_of_tt_helper">The <tt>validates_presence_of</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_uniqueness_of_tt_helper">The <tt>validates_uniqueness_of</tt> helper</a></li>
            
              <li><a href="#_the_tt_validates_each_tt_helper">The <tt>validates_each</tt> helper</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_common_validation_options">Common Validation Options</a>
            <ul>
            
              <li><a href="#_the_tt_allow_nil_tt_option">The <tt>:allow_nil</tt> option</a></li>
            
              <li><a href="#_the_tt_allow_blank_tt_option">The <tt>:allow_blank</tt> option</a></li>
            
              <li><a href="#_the_tt_message_tt_option">The <tt>:message</tt> option</a></li>
            
              <li><a href="#_the_tt_on_tt_option">The <tt>:on</tt> option</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_conditional_validation">Conditional validation</a>
            <ul>
            
              <li><a href="#_using_a_symbol_with_the_tt_if_tt_and_tt_unless_tt_options">Using a symbol with the <tt>:if</tt> and <tt>:unless</tt> options</a></li>
            
              <li><a href="#_using_a_string_with_the_tt_if_tt_and_tt_unless_tt_options">Using a string with the <tt>:if</tt> and <tt>:unless</tt> options</a></li>
            
              <li><a href="#_using_a_proc_object_with_the_tt_if_tt_and_tt_unless_tt_options">Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_writing_your_own_validation_methods">Writing your own validation methods</a>
          </li>
          <li>
          <a href="#_manipulating_the_tt_errors_tt_collection">Manipulating the <tt>errors</tt> collection</a>
          </li>
          <li>
          <a href="#_using_the_tt_errors_tt_collection_in_your_view_templates">Using the <tt>errors</tt> collection in your view templates</a>
            <ul>
            
              <li><a href="#_changing_the_way_form_fields_with_errors_are_displayed">Changing the way form fields with errors are displayed</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_callbacks">Callbacks</a>
            <ul>
            
              <li><a href="#_callbacks_registration">Callbacks registration</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_conditional_callbacks">Conditional callbacks</a>
            <ul>
            
              <li><a href="#_using_a_symbol_with_the_tt_if_tt_and_tt_unless_tt_options_2">Using a symbol with the <tt>:if</tt> and <tt>:unless</tt> options</a></li>
            
              <li><a href="#_using_a_string_with_the_tt_if_tt_and_tt_unless_tt_options_2">Using a string with the <tt>:if</tt> and <tt>:unless</tt> options</a></li>
            
              <li><a href="#_using_a_proc_object_with_the_tt_if_tt_and_tt_unless_tt_options_2">Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</a></li>
            
              <li><a href="#_multiple_conditions_for_callbacks">Multiple Conditions for Callbacks</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_available_callbacks">Available callbacks</a>
            <ul>
            
              <li><a href="#_callbacks_called_both_when_creating_or_updating_a_record">Callbacks called both when creating or updating a record.</a></li>
            
              <li><a href="#_callbacks_called_only_when_creating_a_new_record">Callbacks called only when creating a new record.</a></li>
            
              <li><a href="#_callbacks_called_only_when_updating_an_existing_record">Callbacks called only when updating an existing record.</a></li>
            
              <li><a href="#_callbacks_called_when_removing_a_record_from_the_database">Callbacks called when removing a record from the database.</a></li>
            
              <li><a href="#_the_tt_after_initialize_tt_and_tt_after_find_tt_callbacks">The <tt>after_initialize</tt> and <tt>after_find</tt> callbacks</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_halting_execution">Halting Execution</a>
          </li>
          <li>
          <a href="#_callback_classes">Callback classes</a>
          </li>
          <li>
          <a href="#_observers">Observers</a>
            <ul>
            
              <li><a href="#_registering_observers">Registering observers</a></li>
            
              <li><a href="#_where_to_put_the_observers_source_files">Where to put the observers' source files</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_changelog">Changelog</a>
          </li>
      </ol>
    </div>
    
    <div id="content">
        <h1>Active Record Validations and Callbacks</h1>
      <div id="preamble">
<div class="sectionbody">
<div class="paragraph"><p>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.</p></div>
<div class="paragraph"><p>After reading this guide and trying out the presented concepts, we hope that you&#8217;ll be able to:</p></div>
<div class="ulist"><ul>
<li>
<p>
Use the built-in Active Record validation helpers
</p>
</li>
<li>
<p>
Create your own custom validation methods
</p>
</li>
<li>
<p>
Work with the error messages generated by the validation process
</p>
</li>
<li>
<p>
Create callback methods to respond to events in the object lifecycle.
</p>
</li>
<li>
<p>
Create special classes that encapsulate common behavior for your callbacks
</p>
</li>
<li>
<p>
Create Rails Observers
</p>
</li>
</ul></div>
</div>
</div>
<h2 id="_overview_of_activerecord_validation">1. Overview of ActiveRecord Validation</h2>
<div class="sectionbody">
<div class="paragraph"><p>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?</p></div>
<h3 id="_why_use_activerecord_validations">1.1. Why Use ActiveRecord Validations?</h3>
<div class="paragraph"><p>The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It&#8217;s important to be sure that an email address column only contains valid email addresses, or that the customer&#8217;s name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.</p></div>
<div class="paragraph"><p>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:</p></div>
<div class="ulist"><ul>
<li>
<p>
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.
</p>
</li>
<li>
<p>
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&#8217;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.
</p>
</li>
<li>
<p>
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&#8217;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.
</p>
</li>
</ul></div>
<h3 id="_when_does_validation_happen">1.2. When Does Validation Happen?</h3>
<div class="paragraph"><p>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 <tt>new</tt> method, that object does not belong to the database yet. Once you call <tt>save</tt> upon that object it will be saved into the appropriate database table. Active Record uses the <tt>new_record?</tt> instance method to determine whether an object is already in the database or not. Consider the following simple Active Record class:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>We can see how it works by looking at some script/console output:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&gt;&gt; p = Person.new(:name =&gt; "John Doe", :birthdate =&gt; Date.parse("09/03/1979"))
=&gt; #&lt;Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil&gt;
&gt;&gt; p.new_record?
=&gt; true
&gt;&gt; p.save
=&gt; true
&gt;&gt; p.new_record?
=&gt; false</tt></pre>
</div></div>
<div class="paragraph"><p>Saving new records means sending an SQL <tt>INSERT</tt> operation to the database, while saving existing records (by calling either <tt>save</tt> or <tt>update_attributes</tt>) will result in a SQL <tt>UPDATE</tt> operation. Active Record will use these facts to perform validations upon your objects, keeping them out of 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&#8217;re creating a new record or when you&#8217;re updating an existing one.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/caution.png" alt="Caution" />
</td>
<td class="content">There are four methods that when called will trigger validation: <tt>save</tt>, <tt>save!</tt>, <tt>update_attributes</tt> and <tt>update_attributes!</tt>. There is one update method for Active Record objects left, which is <tt>update_attribute</tt>. This method will update the value of an attribute <em>without</em> triggering any validation. Be careful when using <tt>update_attribute</tt>, because it can let you save your objects in an invalid state.</td>
</tr></table>
</div>
<h3 id="_the_meaning_of_tt_valid_tt">1.3. The Meaning of <tt>valid</tt></h3>
<div class="paragraph"><p>To verify whether an object is valid, Active Record uses the <tt>valid?</tt> 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 <tt>errors</tt> instance method. The process is really simple: If the <tt>errors</tt> 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 <tt>errors</tt> collection.</p></div>
</div>
<h2 id="_the_declarative_validation_helpers">2. The Declarative Validation Helpers</h2>
<div class="sectionbody">
<div class="paragraph"><p>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&#8217;s <tt>errors</tt> collection, and this message is associated with the field being validated.</p></div>
<div class="paragraph"><p>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.</p></div>
<div class="paragraph"><p>All these helpers accept the <tt>:on</tt> and <tt>:message</tt> options, which define when the validation should be applied and what message should be added to the <tt>errors</tt> collection when it fails, respectively. The <tt>:on</tt> option takes one of the values <tt>:save</tt> (the default), <tt>:create</tt>  or <tt>:update</tt>. There is a default error message for each one of the validation helpers. These messages are used when the <tt>:message</tt> option isn&#8217;t used. Let&#8217;s take a look at each one of the available helpers.</p></div>
<h3 id="_the_tt_validates_acceptance_of_tt_helper">2.1. The <tt>validates_acceptance_of</tt> helper</h3>
<div class="paragraph"><p>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&#8217;s terms of service, confirm reading some text, or any similar concept. This validation is very specific to web applications and actually this <em>acceptance</em> does not need to be recorded anywhere in your database (if you don&#8217;t have a field for it, the helper will just create a virtual attribute).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_acceptance_of <span style="color: #990000">:</span>terms_of_service
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The default error message for <tt>validates_acceptance_of</tt> is "<em>must be accepted</em>"</p></div>
<div class="paragraph"><p><tt>validates_acceptance_of</tt> can receive an <tt>:accept</tt> option, which determines the value that will be considered acceptance. It defaults to "1", but you can change this.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_acceptance_of <span style="color: #990000">:</span>terms_of_service<span style="color: #990000">,</span> <span style="color: #990000">:</span>accept <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'yes'</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_the_tt_validates_associated_tt_helper">2.2. The <tt>validates_associated</tt> helper</h3>
<div class="paragraph"><p>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, <tt>valid?</tt> will be called upon each one of the associated objects.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Library <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>books
  validates_associated <span style="color: #990000">:</span>books
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>This validation will work with all the association types.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/caution.png" alt="Caution" />
</td>
<td class="content">Don&#8217;t use <tt>validates_associated</tt> on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.</td>
</tr></table>
</div>
<div class="paragraph"><p>The default error message for <tt>validates_associated</tt> is "<em>is invalid</em>". Note that each associated object will contain its own <tt>errors</tt> collection; errors do not bubble up to the calling model.</p></div>
<h3 id="_the_tt_validates_confirmation_of_tt_helper">2.3. The <tt>validates_confirmation_of</tt> helper</h3>
<div class="paragraph"><p>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 <em>_confirmation</em> appended.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_confirmation_of <span style="color: #990000">:</span>email
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>In your view template you could use something like</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>&lt;%= text_field :person, :email %&gt;
&lt;%= text_field :person, :email_confirmation %&gt;</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">This check is performed only if <tt>email_confirmation</tt> is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we&#8217;ll take a look at <tt>validates_presence_of</tt> later on this guide):</td>
</tr></table>
</div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_confirmation_of <span style="color: #990000">:</span>email
  validates_presence_of <span style="color: #990000">:</span>email_confirmation
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The default error message for <tt>validates_confirmation_of</tt> is "<em>doesn&#8217;t match confirmation</em>"</p></div>
<h3 id="_the_tt_validates_exclusion_of_tt_helper">2.4. The <tt>validates_exclusion_of</tt> helper</h3>
<div class="paragraph"><p>This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> MovieFile <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_exclusion_of <span style="color: #990000">:</span>format<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>mov avi<span style="color: #990000">),</span>
    <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Extension %s is not allowed"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The <tt>validates_exclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will not be accepted for the validated attributes. The <tt>:in</tt> option has an alias called <tt>:within</tt>  that you can use for the same purpose, if you&#8217;d like to. This example uses the <tt>:message</tt> option to show how you can personalize it with the current attribute&#8217;s value, through the <tt>%s</tt> format mask.</p></div>
<div class="paragraph"><p>The default error message for <tt>validates_exclusion_of</tt>  is "<em>is not included in the list</em>".</p></div>
<h3 id="_the_tt_validates_format_of_tt_helper">2.5. The <tt>validates_format_of</tt> helper</h3>
<div class="paragraph"><p>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 <tt>:with</tt> option.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_format_of <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span>
    <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Only letters allowed"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The default error message for <tt>validates_format_of</tt> is "<em>is invalid</em>".</p></div>
<h3 id="_the_tt_validates_inclusion_of_tt_helper">2.6. The <tt>validates_inclusion_of</tt> helper</h3>
<div class="paragraph"><p>This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span>
    <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The <tt>validates_inclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will be accepted. The <tt>:in</tt> option has an alias called <tt>:within</tt> that you can use for the same purpose, if you&#8217;d like to. The previous example uses the <tt>:message</tt> option to show how you can personalize it with the current attribute&#8217;s value, through the <tt>%s</tt> format mask.</p></div>
<div class="paragraph"><p>The default error message for <tt>validates_inclusion_of</tt>  is "<em>is not included in the list</em>".</p></div>
<h3 id="_the_tt_validates_length_of_tt_helper">2.7. The <tt>validates_length_of</tt> helper</h3>
<div class="paragraph"><p>This helper validates the length of your attribute&#8217;s value. It includes a variety of different options, so you can specify length constraints in different ways:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_length_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>minimum <span style="color: #990000">=&gt;</span> <span style="color: #993399">2</span>
  validates_length_of <span style="color: #990000">:</span>bio<span style="color: #990000">,</span> <span style="color: #990000">:</span>maximum <span style="color: #990000">=&gt;</span> <span style="color: #993399">500</span>
  validates_length_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #993399">6</span><span style="color: #990000">..</span><span style="color: #993399">20</span>
  validates_length_of <span style="color: #990000">:</span>registration_number<span style="color: #990000">,</span> <span style="color: #990000">:</span>is <span style="color: #990000">=&gt;</span> <span style="color: #993399">6</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The possible length constraint options are:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>:minimum</tt> - The attribute cannot have less than the specified length.
</p>
</li>
<li>
<p>
<tt>:maximum</tt> - The attribute cannot have more than the specified length.
</p>
</li>
<li>
<p>
<tt>:in</tt> (or <tt>:within</tt>) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
</p>
</li>
<li>
<p>
<tt>:is</tt> - The attribute length must be equal to a given value.
</p>
</li>
</ul></div>
<div class="paragraph"><p>The default error messages depend on the type of length validation being performed. You can personalize these messages, using the <tt>:wrong_length</tt>, <tt>:too_long</tt> and <tt>:too_short</tt> options and the <tt>%d</tt> format mask as a placeholder for the number corresponding to the length constraint being used. You can still use the <tt>:message</tt> option to specify an error message.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_length_of <span style="color: #990000">:</span>bio<span style="color: #990000">,</span> <span style="color: #990000">:</span>too_long <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"you're writing too much. %d characters is the maximum allowed."</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The <tt>validates_size_of</tt> helper is an alias for <tt>validates_length_of</tt>.</p></div>
<h3 id="_the_tt_validates_numericality_of_tt_helper">2.8. The <tt>validates_numericality_of</tt> helper</h3>
<div class="paragraph"><p>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 <tt>:integer_only</tt> option set to true, you can specify that only integral numbers are allowed.</p></div>
<div class="paragraph"><p>If you set <tt>:integer_only</tt> to <tt>true</tt>, then it will use the <tt>$$/\A[</tt>\-]?\d+\Z/<tt> regular expression to validate the attribute&#8217;s value. Otherwise, it will try to convert the value to a number using +Kernel.Float</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Player <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_numericality_of <span style="color: #990000">:</span>points
  validates_numericality_of <span style="color: #990000">:</span>games_played<span style="color: #990000">,</span> <span style="color: #990000">:</span>only_integer <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Besides <tt>:only_integer</tt>, the <tt>validates_numericality_of</tt> helper also accepts the following options to add constraints to acceptable values:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>:greater_than</tt> - Specifies the value must be greater than the supplied value. The default error message for this option is "<em>must be greater than (value)</em>"
</p>
</li>
<li>
<p>
<tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value. The default error message for this option is "<em>must be greater than or equal to (value)</em>"
</p>
</li>
<li>
<p>
<tt>:equal_to</tt> - Specifies the value must be equal to the supplied value. The default error message for this option is "<em>must be equal to (value)</em>"
</p>
</li>
<li>
<p>
<tt>:less_than</tt> - Specifies the value must be less than the supplied value. The default error message for this option is "<em>must e less than (value)</em>"
</p>
</li>
<li>
<p>
<tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value. The default error message for this option is "<em>must be less or equal to (value)</em>"
</p>
</li>
<li>
<p>
<tt>:odd</tt> - Specifies the value must be an odd number if set to true. The default error message for this option is "<em>must be odd</em>"
</p>
</li>
<li>
<p>
<tt>:even</tt> - Specifies the value must be an even number if set to true. The default error message for this option is "<em>must be even</em>"
</p>
</li>
</ul></div>
<div class="paragraph"><p>The default error message for <tt>validates_numericality_of</tt> is "<em>is not a number</em>".</p></div>
<h3 id="_the_tt_validates_presence_of_tt_helper">2.9. The <tt>validates_presence_of</tt> helper</h3>
<div class="paragraph"><p>This helper validates that the specified attributes are not empty. It uses the <tt>blank?</tt> method to check if the value is either <tt>nil</tt> or an empty string (if the string has only spaces, it will still be considered empty).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>login<span style="color: #990000">,</span> <span style="color: #990000">:</span>email
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">If you want to be sure that an association is present, you&#8217;ll need to test whether the foreign key used to map the association is present, and not the associated object itself.</td>
</tr></table>
</div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>order
  validates_presence_of <span style="color: #990000">:</span>order_id
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">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 =&gt; [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # =&gt; true</td>
</tr></table>
</div>
<div class="paragraph"><p>The default error message for <tt>validates_presence_of</tt> is "<em>can&#8217;t be empty</em>".</p></div>
<h3 id="_the_tt_validates_uniqueness_of_tt_helper">2.10. The <tt>validates_uniqueness_of</tt> helper</h3>
<div class="paragraph"><p>This helper validates that the attribute&#8217;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.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_uniqueness_of <span style="color: #990000">:</span>email
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The validation happens by performing a SQL query into the model&#8217;s table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.</p></div>
<div class="paragraph"><p>There is a <tt>:scope</tt> option that you can use to specify other attributes that are used to limit the uniqueness check:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Holiday <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span>
    <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Should happen once per year"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>There is also a <tt>:case_sensitive</tt> option that you can use to define whether the uniqueness constraint will be case sensitive or not. This option defaults to true.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>case_sensitive <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The default error message for <tt>validates_uniqueness_of</tt> is "<em>has already been taken</em>".</p></div>
<h3 id="_the_tt_validates_each_tt_helper">2.11. The <tt>validates_each</tt> helper</h3>
<div class="paragraph"><p>This helper validates attributes against a block. It doesn&#8217;t have a predefined validation function. You should create one using a block, and every attribute passed to <tt>validates_each</tt> will be tested against it. In the following example, we don&#8217;t want names and surnames to begin with lower case.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_each <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>surname <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>model<span style="color: #990000">,</span> attr<span style="color: #990000">,</span> value<span style="color: #990000">|</span>
    model<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>add<span style="color: #990000">(</span>attr<span style="color: #990000">,</span> <span style="color: #FF0000">'Must start with upper case'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> value <span style="color: #990000">=~</span> <span style="color: #FF6600">/^[a-z]/</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The block receives the model, the attribute&#8217;s name and the attribute&#8217;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.</p></div>
</div>
<h2 id="_common_validation_options">3. Common Validation Options</h2>
<div class="sectionbody">
<div class="paragraph"><p>There are some common options that all the validation helpers can use. Here they are, except for the <tt>:if</tt> and <tt>:unless</tt> options, which are discussed later in the conditional validation topic.</p></div>
<h3 id="_the_tt_allow_nil_tt_option">3.1. The <tt>:allow_nil</tt> option</h3>
<div class="paragraph"><p>The <tt>:allow_nil</tt> option skips the validation when the value being validated is <tt>nil</tt>. You may be asking yourself if it makes any sense to use <tt>:allow_nil</tt> and <tt>validates_presence_of</tt> together. Well, it does. Remember, the validation will be skipped only for <tt>nil</tt> attributes, but empty strings are not considered <tt>nil</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span>
    <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>allow_nil <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_the_tt_allow_blank_tt_option">3.2. The <tt>:allow_blank</tt> option</h3>
<div class="paragraph"><p>The <tt>:allow_blank: option is similar to the +:allow_nil</tt> option. This option will let validation pass if the attribute&#8217;s value is <tt>nil</tt> or an empty string, i.e., any value that returns <tt>true</tt> for <tt>blank?</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Topic <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_length_of <span style="color: #990000">:</span>title<span style="color: #990000">,</span> <span style="color: #990000">:</span>is <span style="color: #990000">=&gt;</span> <span style="color: #993399">5</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>allow_blank <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

Topic<span style="color: #990000">.</span>create<span style="color: #990000">(</span><span style="color: #FF0000">"title"</span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">""</span><span style="color: #990000">).</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; true</span></span>
Topic<span style="color: #990000">.</span>create<span style="color: #990000">(</span><span style="color: #FF0000">"title"</span> <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">).</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; true</span></span></tt></pre></div></div>
<h3 id="_the_tt_message_tt_option">3.3. The <tt>:message</tt> option</h3>
<div class="paragraph"><p>As you&#8217;ve already seen, the <tt>:message</tt> option lets you specify the message that will be added to the <tt>errors</tt> 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.</p></div>
<h3 id="_the_tt_on_tt_option">3.4. The <tt>:on</tt> option</h3>
<div class="paragraph"><p>The <tt>:on</tt> 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&#8217;re creating a new record and when you&#8217;re updating it). If you want to change it, you can use <tt>:on =&gt; :create</tt> to run the validation only when a new record is created or <tt>:on =&gt; :update</tt> to run the validation only when a record is updated.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to update email with a duplicated value</span></span>
  validates_uniqueness_of <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create

  <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to create the record with a 'non-numerical age'</span></span>
  validates_numericality_of <span style="color: #990000">:</span>age<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>update

  <span style="font-style: italic"><span style="color: #9A1900"># =&gt; the default (validates on both create and update)</span></span>
  validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>save
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
</div>
<h2 id="_conditional_validation">4. Conditional validation</h2>
<div class="sectionbody">
<div class="paragraph"><p>Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the <tt>:if</tt> and <tt>:unless</tt> options, which can take a symbol, a string or a Ruby Proc. You may use the <tt>:if</tt> option when you want to specify when the validation <strong>should</strong> happen. If you want to specify when the validation <strong>should not</strong> happen, then you may use the <tt>:unless</tt> option.</p></div>
<h3 id="_using_a_symbol_with_the_tt_if_tt_and_tt_unless_tt_options">4.1. Using a symbol with the <tt>:if</tt> and <tt>:unless</tt> options</h3>
<div class="paragraph"><p>You can associate the <tt>:if</tt> and <tt>:unless</tt> 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.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_presence_of <span style="color: #990000">:</span>card_number<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>paid_with_card?

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> paid_with_card?
    payment_type <span style="color: #990000">==</span> <span style="color: #FF0000">"card"</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_using_a_string_with_the_tt_if_tt_and_tt_unless_tt_options">4.2. Using a string with the <tt>:if</tt> and <tt>:unless</tt> options</h3>
<div class="paragraph"><p>You can also use a string that will be evaluated using <tt>:eval</tt> and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_presence_of <span style="color: #990000">:</span>surname<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"name.nil?"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_using_a_proc_object_with_the_tt_if_tt_and_tt_unless_tt_options">4.3. Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</h3>
<div class="paragraph"><p>Finally, it&#8217;s possible to associate <tt>:if</tt> and <tt>:unless</tt> 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.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_confirmation_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span>
    <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>a<span style="color: #990000">|</span> a<span style="color: #990000">.</span>password<span style="color: #990000">.</span>blank? <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
</div>
<h2 id="_writing_your_own_validation_methods">5. Writing your own validation methods</h2>
<div class="sectionbody">
<div class="paragraph"><p>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 <tt>errors</tt> collection when they are invalid. You must then register those methods by using one or more of the <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> 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.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validate <span style="color: #990000">:</span>expiration_date_cannot_be_in_the_past<span style="color: #990000">,</span>
    <span style="color: #990000">:</span>discount_cannot_be_more_than_total_value

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> expiration_date_cannot_be_in_the_past
    errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span>
      <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> discount_cannot_be_greater_than_total_value
    errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>discount<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be greater than total value"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span>
      discount <span style="color: #990000">&lt;=</span> total_value
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>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:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> ActiveRecord
  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Validations
    <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> ClassMethods
      <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> validates_email_format_of<span style="color: #990000">(</span>value<span style="color: #990000">)</span>
        validates_format_of value<span style="color: #990000">,</span>
          <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #FF6600">/\A[\w\._%-]+@[\w\.-]+\.[a-zA-Z]{2,4}\z/</span><span style="color: #990000">,</span>
          <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>u<span style="color: #990000">|</span> <span style="color: #990000">!</span>u<span style="color: #990000">.</span>email<span style="color: #990000">.</span>blank? <span style="color: #FF0000">}</span><span style="color: #990000">,</span>
          <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Invalid format for email address"</span>
      <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The recipe is simple: just create a new validation method inside the <tt>ActiveRecord::Validations::ClassMethods</tt> module. You can put this code in a file inside your application&#8217;s <strong>lib</strong> folder, and then requiring it from your <strong>environment.rb</strong> or any other file inside <strong>config/initializers</strong>. You can use this helper like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_email_format_of <span style="color: #990000">:</span>email_address
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
</div>
<h2 id="_manipulating_the_tt_errors_tt_collection">6. Manipulating the <tt>errors</tt> collection</h2>
<div class="sectionbody">
<div class="paragraph"><p>You can do more than just call <tt>valid?</tt> upon your objects based on the existance of the <tt>errors</tt> collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object&#8217;s state.</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>add_to_base</tt> lets you add errors messages that are related to the object&#8217;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&#8217;s attributes. <tt>add_to_base</tt> receives a string with the message.
</p>
</li>
</ul></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> a_method_used_for_validation_purposes
    errors<span style="color: #990000">.</span>add_to_base<span style="color: #990000">(</span><span style="color: #FF0000">"This person is invalid because ..."</span><span style="color: #990000">)</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="ulist"><ul>
<li>
<p>
<tt>add</tt> 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. <tt>add</tt> receives a symbol with the name of the attribute that you want to add the message to and the message itself.
</p>
</li>
</ul></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> a_method_used_for_validation_purposes
    errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>name<span style="color: #990000">,</span> <span style="color: #FF0000">"can't have the characters !@#$%*()_-+="</span><span style="color: #990000">)</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="ulist"><ul>
<li>
<p>
<tt>invalid?</tt> 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.
</p>
</li>
</ul></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>email
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new<span style="color: #990000">(:</span>name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"John Doe"</span><span style="color: #990000">)</span>
person<span style="color: #990000">.</span>invalid?<span style="color: #990000">(:</span>email<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># =&gt; true</span></span></tt></pre></div></div>
<div class="ulist"><ul>
<li>
<p>
<tt>on</tt> 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 <tt>errors</tt> collection for the given attribute. If there are no errors related to the attribute, <tt>on</tt> will return <tt>nil</tt>. If there is just one errors message for this attribute, <tt>on</tt> will return a string with the message. When <tt>errors</tt> holds two or more error messages for the attribute, <tt>on</tt> will return an array of strings, each one with one error message.
</p>
</li>
</ul></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_presence_of <span style="color: #990000">:</span>name
  validates_length_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>minimum <span style="color: #990000">=&gt;</span> <span style="color: #993399">3</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new<span style="color: #990000">(:</span>name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"John Doe"</span><span style="color: #990000">)</span>
person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; true</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># =&gt; nil</span></span>

person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new<span style="color: #990000">(:</span>name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"JD"</span><span style="color: #990000">)</span>
person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; "is too short (minimum is 3 characters)"</span></span>

person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new
person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span></tt></pre></div></div>
<div class="ulist"><ul>
<li>
<p>
<tt>clear</tt> is used when you intentionally want to clear all the messages in the <tt>errors</tt> collection. However, calling <tt>errors.clear</tt> upon an invalid object won&#8217;t make it valid: the <tt>errors</tt> collection will now be empty, but the next time you call <tt>valid?</tt> or any method that tries to save this object to the database, the validations will run. If any of them fails, the <tt>errors</tt> collection will get filled again.
</p>
</li>
</ul></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_presence_of <span style="color: #990000">:</span>name
  validates_length_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>minimum <span style="color: #990000">=&gt;</span> <span style="color: #993399">3</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new
person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>

person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>clear
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>empty? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; true</span></span>
p<span style="color: #990000">.</span>save <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
p<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
<span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span></tt></pre></div></div>
</div>
<h2 id="_using_the_tt_errors_tt_collection_in_your_view_templates">7. Using the <tt>errors</tt> collection in your view templates</h2>
<div class="sectionbody">
<div class="paragraph"><p>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.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_presence_of <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>value
  validates_numericality_of <span style="color: #990000">:</span>value<span style="color: #990000">,</span> <span style="color: #990000">:</span>allow_nil <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% form_for(@product) do |f| %&gt;
  &lt;%= f.error_messages %&gt;
  &lt;p&gt;
    &lt;%= f.label :description %&gt;&lt;br /&gt;
    &lt;%= f.text_field :description %&gt;
  &lt;/p&gt;
  &lt;p&gt;
    &lt;%= f.label :value %&gt;&lt;br /&gt;
    &lt;%= f.text_field :value %&gt;
  &lt;/p&gt;
  &lt;p&gt;
    &lt;%= f.submit "Create" %&gt;
  &lt;/p&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="imageblock">
<div class="content">
<img src="images/error_messages.png" alt="Error messages" title="Error messages"/>
</div>
</div>
<div class="paragraph"><p>You can also use the <tt>error_messages_for</tt> helper to display the error messages of a model assigned to a view template. It&#8217;s very similar to the previous example and will achieve exactly the same result.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= error_messages_for :product %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>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.</p></div>
<div class="paragraph"><p>Both the <tt>form.error_messages</tt> and the <tt>error_messages_for</tt> helpers accept options that let you customize the <tt>div</tt> 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.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= f.error_messages :header_message =&gt; "Invalid product!",
  :message =&gt; "You'll need to fix the following fields:",
  :header_tag =&gt; :h3 %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>Which results in the following content</p></div>
<div class="imageblock">
<div class="content">
<img src="images/customized_error_messages.png" alt="Customized error messages" title="Customized error messages"/>
</div>
</div>
<div class="paragraph"><p>If you pass <tt>nil</tt> to any of these options, it will get rid of the respective section of the <tt>div</tt>.</p></div>
<div class="paragraph"><p>It&#8217;s also possible to change the CSS classes used by the <tt>error_messages</tt> helper. These classes are automatically defined at the <strong>scaffold.css</strong> file, generated by the scaffold script. If you&#8217;re not using scaffolding, you can still define those CSS classes at your CSS files. Here is a list of the default CSS classes.</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>.fieldWithErrors</tt> - Style for the form fields with errors.
</p>
</li>
<li>
<p>
<tt>#errorExplanation</tt> - Style for the <tt>div</tt> element with the error messages.
</p>
</li>
<li>
<p>
<tt>#errorExplanation h2</tt> - Style for the header of the <tt>div</tt> element.
</p>
</li>
<li>
<p>
<tt>#errorExplanation p</tt> - Style for the paragraph that holds the message that appears right below the header of the <tt>div</tt> element.
</p>
</li>
<li>
<p>
<tt>#errorExplanation ul li</tt> - Style for the list of error messages.
</p>
</li>
</ul></div>
<h3 id="_changing_the_way_form_fields_with_errors_are_displayed">7.1. Changing the way form fields with errors are displayed</h3>
<div class="paragraph"><p>By default, form fields with errors are displayed enclosed by a <tt>div</tt> element with the <tt>fieldWithErrors</tt> 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 <tt>span</tt> element with a <tt>validation-error</tt> CSS class. There will be no <tt>div</tt> element enclosing the <tt>input</tt> element, so we get rid of that red border around the text field. You can use the <tt>validation-error</tt> CSS class to style it anyway you want.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>ActionView<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>field_error_proc <span style="color: #990000">=</span> Proc<span style="color: #990000">.</span>new <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>html_tag<span style="color: #990000">,</span> instance<span style="color: #990000">|</span>
  <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> instance<span style="color: #990000">.</span>error_message<span style="color: #990000">.</span>kind_of?<span style="color: #990000">(</span>Array<span style="color: #990000">)</span>
    <span style="color: #990000">%(#</span><span style="color: #FF0000">{</span>html_tag<span style="color: #FF0000">}</span><span style="color: #FF0000">&lt;span class='validation-error'&gt;</span><span style="color: #990000">&amp;</span>nbsp<span style="color: #990000">;</span>
      <span style="color: #990000">#</span><span style="color: #FF0000">{</span>instance<span style="color: #990000">.</span>error_message<span style="color: #990000">.</span>join<span style="color: #990000">(</span><span style="color: #FF0000">','</span><span style="color: #990000">)</span><span style="color: #FF0000">}</span><span style="color: #FF0000">&lt;/span&gt;</span><span style="color: #990000">)</span>
  <span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
    <span style="color: #990000">%(#</span><span style="color: #FF0000">{</span>html_tag<span style="color: #FF0000">}</span><span style="color: #FF0000">&lt;span class='validation-error'&gt;</span><span style="color: #990000">&amp;</span>nbsp<span style="color: #990000">;</span>
      <span style="color: #990000">#</span><span style="color: #FF0000">{</span>instance<span style="color: #990000">.</span>error_message<span style="color: #FF0000">}</span><span style="color: #FF0000">&lt;/span&gt;</span><span style="color: #990000">)</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>This will result in something like the following content:</p></div>
<div class="imageblock">
<div class="content">
<img src="images/validation_error_messages.png" alt="Validation error messages" title="Validation error messages"/>
</div>
</div>
<div class="paragraph"><p>The way form fields with errors are treated is defined by the <tt>ActionView::Base.field_error_proc</tt> Ruby Proc. This Proc receives two parameters:</p></div>
<div class="ulist"><ul>
<li>
<p>
A string with the HTML tag
</p>
</li>
<li>
<p>
An object of the <tt>ActionView::Helpers::InstanceTag</tt> class.
</p>
</li>
</ul></div>
</div>
<h2 id="_callbacks">8. Callbacks</h2>
<div class="sectionbody">
<div class="paragraph"><p>Callbacks are methods that get called at certain moments of an object&#8217;s lifecycle. With callbacks it&#8217;s possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database.</p></div>
<h3 id="_callbacks_registration">8.1. Callbacks registration</h3>
<div class="paragraph"><p>In order to use the available callbacks, you need to registrate 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.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> User <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_presence_of <span style="color: #990000">:</span>login<span style="color: #990000">,</span> <span style="color: #990000">:</span>email

  before_validation <span style="color: #990000">:</span>ensure_login_has_a_value

  protected
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> ensure_login_has_a_value
    <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>login<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
      <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>login <span style="color: #990000">=</span> email <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> email<span style="color: #990000">.</span>blank?
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>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.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> User <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  validates_presence_of <span style="color: #990000">:</span>login<span style="color: #990000">,</span> <span style="color: #990000">:</span>email

  before_create <span style="color: #FF0000">{</span><span style="color: #990000">|</span>user<span style="color: #990000">|</span> user<span style="color: #990000">.</span>name <span style="color: #990000">=</span> user<span style="color: #990000">.</span>login<span style="color: #990000">.</span>capitalize <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> user<span style="color: #990000">.</span>name<span style="color: #990000">.</span>blank?<span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/caution.png" alt="Caution" />
</td>
<td class="content">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.</td>
</tr></table>
</div>
</div>
<h2 id="_conditional_callbacks">9. Conditional callbacks</h2>
<div class="sectionbody">
<div class="paragraph"><p>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 <tt>:if</tt> and <tt>:unless</tt> options, which can take a symbol, a string or a Ruby Proc. You may use the <tt>:if</tt> option when you want to specify when the callback <strong>should</strong> get called. If you want to specify when the callback <strong>should not</strong> be called, then you may use the <tt>:unless</tt> option.</p></div>
<h3 id="_using_a_symbol_with_the_tt_if_tt_and_tt_unless_tt_options_2">9.1. Using a symbol with the <tt>:if</tt> and <tt>:unless</tt> options</h3>
<div class="paragraph"><p>You can associate the <tt>:if</tt> and <tt>:unless</tt> options with a symbol corresponding to the name of a method that will get called right before the callback. If this method returns <tt>false</tt> the callback won&#8217;t be executed. This is the most common option. Using this form of registration it&#8217;s also possible to register several different methods that should be called to check the if the callback should be executed.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  before_save <span style="color: #990000">:</span>normalize_card_number<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>paid_with_card?
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_using_a_string_with_the_tt_if_tt_and_tt_unless_tt_options_2">9.2. Using a string with the <tt>:if</tt> and <tt>:unless</tt> options</h3>
<div class="paragraph"><p>You can also use a string that will be evaluated using <tt>:eval</tt> and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  before_save <span style="color: #990000">:</span>normalize_card_number<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"paid_with_card?"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_using_a_proc_object_with_the_tt_if_tt_and_tt_unless_tt_options_2">9.3. Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</h3>
<div class="paragraph"><p>Finally, it&#8217;s possible to associate <tt>:if</tt> and <tt>:unless</tt> with a Ruby Proc object. This option is best suited when writing short validation methods, usually one-liners.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  before_save <span style="color: #990000">:</span>normalize_card_number<span style="color: #990000">,</span>
    <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>order<span style="color: #990000">|</span> order<span style="color: #990000">.</span>paid_with_card? <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_multiple_conditions_for_callbacks">9.4. Multiple Conditions for Callbacks</h3>
<div class="paragraph"><p>When writing conditional callbacks, it&#8217;s possible to mix both <tt>:if</tt> and <tt>:unless</tt> in the same callback declaration.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Comment <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  after_create <span style="color: #990000">:</span>send_email_to_author<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>author_wants_emails?<span style="color: #990000">,</span>
    <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>comment<span style="color: #990000">|</span> comment<span style="color: #990000">.</span>post<span style="color: #990000">.</span>ignore_comments? <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
</div>
<h2 id="_available_callbacks">10. Available callbacks</h2>
<div class="sectionbody">
<div class="paragraph"><p>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.</p></div>
<h3 id="_callbacks_called_both_when_creating_or_updating_a_record">10.1. Callbacks called both when creating or updating a record.</h3>
<div class="ulist"><ul>
<li>
<p>
<tt>before_validation</tt>
</p>
</li>
<li>
<p>
<tt>after_validation</tt>
</p>
</li>
<li>
<p>
<tt>before_save</tt>
</p>
</li>
<li>
<p>
<strong>INSERT OR UPDATE OPERATION</strong>
</p>
</li>
<li>
<p>
<tt>after_save</tt>
</p>
</li>
</ul></div>
<h3 id="_callbacks_called_only_when_creating_a_new_record">10.2. Callbacks called only when creating a new record.</h3>
<div class="ulist"><ul>
<li>
<p>
<tt>before_validation_on_create</tt>
</p>
</li>
<li>
<p>
<tt>after_validation_on_create</tt>
</p>
</li>
<li>
<p>
<tt>before_create</tt>
</p>
</li>
<li>
<p>
<strong>INSERT OPERATION</strong>
</p>
</li>
<li>
<p>
<tt>after_create</tt>
</p>
</li>
</ul></div>
<h3 id="_callbacks_called_only_when_updating_an_existing_record">10.3. Callbacks called only when updating an existing record.</h3>
<div class="ulist"><ul>
<li>
<p>
<tt>before_validation_on_update</tt>
</p>
</li>
<li>
<p>
<tt>after_validation_on_update</tt>
</p>
</li>
<li>
<p>
<tt>before_update</tt>
</p>
</li>
<li>
<p>
<strong>UPDATE OPERATION</strong>
</p>
</li>
<li>
<p>
<tt>after_update</tt>
</p>
</li>
</ul></div>
<h3 id="_callbacks_called_when_removing_a_record_from_the_database">10.4. Callbacks called when removing a record from the database.</h3>
<div class="ulist"><ul>
<li>
<p>
<tt>before_destroy</tt>
</p>
</li>
<li>
<p>
<strong>DELETE OPERATION</strong>
</p>
</li>
<li>
<p>
<tt>after_destroy</tt>
</p>
</li>
</ul></div>
<div class="paragraph"><p>The <tt>before_destroy</tt> and <tt>after_destroy</tt> callbacks will only be called if you delete the model using either the <tt>destroy</tt> instance method or one of the <tt>destroy</tt> or <tt>destroy_all</tt> class methods of your Active Record class. If you use <tt>delete</tt> or <tt>delete_all</tt> no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database.</p></div>
<h3 id="_the_tt_after_initialize_tt_and_tt_after_find_tt_callbacks">10.5. The <tt>after_initialize</tt> and <tt>after_find</tt> callbacks</h3>
<div class="paragraph"><p>The <tt>after_initialize</tt> callback will be called whenever an Active Record object is instantiated, either by direcly using <tt>new</tt> or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record <tt>initialize</tt> method.</p></div>
<div class="paragraph"><p>The <tt>after_find</tt> callback will be called whenever Active Record loads a record from the database. When used together with <tt>after_initialize</tt> 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.</p></div>
<div class="paragraph"><p>The <tt>after_initialize</tt> and <tt>after_find</tt> 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 <tt>after_initialize</tt> or <tt>after_find</tt> using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since <tt>after_initialize</tt> and <tt>after_find</tt> will both be called for each record found in the database, significantly slowing down the queries.</p></div>
</div>
<h2 id="_halting_execution">11. Halting Execution</h2>
<div class="sectionbody">
<div class="paragraph"><p>As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model&#8217;s validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the <tt>before_create</tt>, <tt>before_save</tt>, <tt>before_update</tt> or <tt>before_destroy</tt> callback methods returns a boolean <tt>false</tt> (not <tt>nil</tt>) 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&#8217;s because the whole callback chain is wrapped in a transaction, so raising an exception or returning <tt>false</tt> fires a database ROLLBACK.</p></div>
</div>
<h2 id="_callback_classes">12. Callback classes</h2>
<div class="sectionbody">
<div class="paragraph"><p>Sometimes the callback methods that you&#8217;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.</p></div>
<div class="paragraph"><p>Here&#8217;s an example where we create a class with a after_destroy callback for a PictureFile model.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PictureFileCallbacks
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> after_destroy<span style="color: #990000">(</span>picture_file<span style="color: #990000">)</span>
    File<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>picture_file<span style="color: #990000">.</span>filepath<span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> File<span style="color: #990000">.</span>exists?<span style="color: #990000">(</span>picture_file<span style="color: #990000">.</span>filepath<span style="color: #990000">)</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PictureFile <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  after_destroy PictureFileCallbacks<span style="color: #990000">.</span>new
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>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.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PictureFileCallbacks
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>after_destroy<span style="color: #990000">(</span>picture_file<span style="color: #990000">)</span>
    File<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>picture_file<span style="color: #990000">.</span>filepath<span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> File<span style="color: #990000">.</span>exists?<span style="color: #990000">(</span>picture_file<span style="color: #990000">.</span>filepath<span style="color: #990000">)</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If the callback method is declared this way, it won&#8217;t be necessary to instantiate a PictureFileCallbacks object.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PictureFile <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  after_destroy PictureFileCallbacks
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>You can declare as many callbacks as you want inside your callback classes.</p></div>
</div>
<h2 id="_observers">13. Observers</h2>
<div class="sectionbody">
<div class="paragraph"><p>Active Record callbacks are a powerful feature, but they can pollute your model implementation with code that&#8217;s not directly related to the model&#8217;s purpose. In object-oriented software, it&#8217;s always a good idea to design your classes with a single responsibility in the whole system. For example, it wouldn&#8217;t make much sense to have a <tt>User</tt> model with a method that writes data about a login attempt to a log file. Whenever you&#8217;re using callbacks to write code that&#8217;s not directly related to your model class purposes, it may be a good moment to create an Observer.</p></div>
<div class="paragraph"><p>An Active Record Observer is an object that links itself to a model and registers its methods for callbacks. Your model&#8217;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&#8217;s implementation.</p></div>
<div class="paragraph"><p>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 <em>Observer</em> part to find the name of the Active Record class to observe.</p></div>
<div class="paragraph"><p>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&#8217;s purpose, we could create an Observer to do just that:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> RegistrationObserver <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Observer
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> after_create<span style="color: #990000">(</span>model<span style="color: #990000">)</span>
    <span style="font-style: italic"><span style="color: #9A1900"># code to send registration confirmation emails...</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Like in callback classes, the observer&#8217;s methods receive the observed model as a parameter.</p></div>
<div class="paragraph"><p>Sometimes using the ModelName + Observer naming convention won&#8217;t be the best choice, mainly when you want to use the same observer for more than one model class. It&#8217;s possible to explicity specify the models that our observer should observe.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Auditor <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Observer
  observe User<span style="color: #990000">,</span> Registration<span style="color: #990000">,</span> Invoice
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_registering_observers">13.1. Registering observers</h3>
<div class="paragraph"><p>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&#8217;s <strong>config/environment.rb</strong> file. In this file there is a commented-out line where we can define the observers that our application should load at start-up.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># Activate observers that should always be running</span></span>
config<span style="color: #990000">.</span>active_record<span style="color: #990000">.</span>observers <span style="color: #990000">=</span> <span style="color: #990000">:</span>registration_observer<span style="color: #990000">,</span> <span style="color: #990000">:</span>auditor</tt></pre></div></div>
<div class="paragraph"><p>You can uncomment the line with <tt>config.active_record.observers</tt> and change the symbols for the name of the observers that should be registered.</p></div>
<div class="paragraph"><p>It&#8217;s also possible to register callbacks in any of the files living at <strong>config/environments/</strong>, if you want an observer to work only in a specific environment. There is not a <tt>config.active_record.observers</tt> line at any of those files, but you can simply add it.</p></div>
<h3 id="_where_to_put_the_observers_source_files">13.2. Where to put the observers' source files</h3>
<div class="paragraph"><p>By convention, you should always save your observers' source files inside <strong>app/models</strong>.</p></div>
</div>
<h2 id="_changelog">14. Changelog</h2>
<div class="sectionbody">
<div class="paragraph"><p><a href="http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks">Lighthouse ticket</a></p></div>
<div class="paragraph"><p>January 9, 2009: Initial version by <a href="http://guides.rails.info/authors.html#cmarques">Cássio Marques</a></p></div>
</div>

    </div>
  </div>
</body>
</html>