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
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
|
<!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" />
<style type="text/css">
div#container {
max-width: 900px;
padding-bottom: 3em;
}
div#content {
margin-left: 200px;
}
div#container.notoc {
max-width: 600px;
}
.notoc div#content {
margin-left: 0;
}
pre {
line-height: 1.4em;
}
#content p tt {
background: #eeeeee;
border: solid 1px #cccccc;
padding: 3px;
}
dt {
font-weight: bold;
}
#content dt tt {
font-size: 10pt;
}
dd {
margin-left: 3em;
}
#content dt tt, #content pre tt {
background: none;
padding: 0;
border: 0;
}
#content .olist ol {
margin-left: 2em;
}
#header {
position: relative;
max-width: 840px;
margin-left: auto;
margin-right: auto;
}
#header.notoc {
max-width: 580px;
}
#logo {
position: absolute;
left: 10px;
top: 10px;
width: 110px;
height: 140px;
}
div#header h1#site_title {
background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
position: absolute;
width: 392px;
height: 55px;
left: 145px;
top: 20px;
margin: 0;
padding: 0;
}
#site_title span {
display: none;
}
#site_title_tagline {
display: none;
}
ul#navMain {
position: absolute;
margin: 0;
padding: 0;
top: 97px;
left: 145px;
}
.left-floaty, .right-floaty {
padding: 15px;
}
.admonitionblock,
.tableblock {
margin-left: 1em;
margin-right: 1em;
margin-top: 0.25em;
margin-bottom: 1em;
}
.admonitionblock .icon {
padding-right: 8px;
}
.admonitionblock .content {
border: solid 1px #ffda78;
background: #fffebd;
padding: 10px;
padding-top: 8px;
padding-bottom: 8px;
}
.admonitionblock .title {
font-size: 140%;
margin-bottom: 0.5em;
}
.tableblock table {
border: solid 1px #aaaaff;
background: #f0f0ff;
}
.tableblock th {
background: #e0e0e0;
}
.tableblock th,
.tableblock td {
padding: 3px;
padding-left: 5px;
padding-right: 5px;
}
.sidebarblock {
margin-top: 0.25em;
margin: 1em;
border: solid 1px #ccccbb;
padding: 8px;
background: #ffffe0;
}
.sidebarblock .sidebar-title {
font-size: 140%;
font-weight: 600;
margin-bottom: 0.3em;
}
.sidebarblock .sidebar-content > .para:last-child > p {
margin-bottom: 0;
}
.sidebarblock .sidebar-title a {
text-decoration: none;
}
.sidebarblock .sidebar-title a:hover {
text-decoration: underline;
}
</style>
</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="#_motivations_to_validate_your_active_record_objects">Motivations to validate your Active Record objects</a>
</li>
<li>
<a href="#_how_it_works">How it works</a>
<ul>
<li><a href="#_when_does_validation_happen">When does validation happen?</a></li>
<li><a href="#_the_meaning_of_em_valid_em">The meaning of <em>valid</em></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 work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles.</p></div>
<div class="paragraph"><p>After reading this guide and trying out the presented concepts, we hope that you’ll be able to:</p></div>
<div class="ulist"><ul>
<li>
<p>
Correctly use all 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>
Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved.
</p>
</li>
<li>
<p>
Create special classes that encapsulate common behaviour for your callbacks
</p>
</li>
<li>
<p>
Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
</p>
</li>
</ul></div>
</div>
</div>
<h2 id="_motivations_to_validate_your_active_record_objects">1. Motivations to validate your Active Record objects</h2>
<div class="sectionbody">
<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’s important to be sure that an email address column only contains valid email addresses, or that the customer’s name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.</p></div>
<div class="paragraph"><p>There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons:</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 mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level.
</p>
</li>
<li>
<p>
Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user’s browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
</p>
</li>
<li>
<p>
Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it’s also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods.
</p>
</li>
</ul></div>
</div>
<h2 id="_how_it_works">2. How it works</h2>
<div class="sectionbody">
<h3 id="_when_does_validation_happen">2.1. 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 who 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’ll be recorded to it’s table. Active Record uses the <tt>new_record?</tt> instance method to discover if an object is already in the database or not. Consider the following simple and very creative 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"><</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 the following script/console output:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>>> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
=> #<Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil>
>> p.new_record?
=> true
>> p.save
=> true
>> p.new_record?
=> false</tt></pre>
</div></div>
<div class="paragraph"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use these facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you’re creating a new record or when you’re updating an existing one.</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 method left, which is <tt>update_attribute</tt>. This method will update the value of an attribute without triggering any validation, so be careful when using <tt>update_attribute</tt>, since it can let you save your objects in an invalid state.</td>
</tr></table>
</div>
<h3 id="_the_meaning_of_em_valid_em">2.2. The meaning of <em>valid</em></h3>
<div class="paragraph"><p>For verifying if 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 proccess 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">3. 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 validations rules that are commonly used in most of the applications that you’ll write, so you don’t need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object’s <tt>errors</tt> collection, this message being associated with the field being validated.</p></div>
<div class="paragraph"><p>Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.</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> (it’s 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’t used. Let’s take a look at each one of the available helpers, listed in alphabetic order.</p></div>
<h3 id="_the_tt_validates_acceptance_of_tt_helper">3.1. The <tt>validates_acceptance_of</tt> helper</h3>
<div class="paragraph"><p>Validates that a checkbox has been checked for agreement purposes. It’s normally used when the user needs to agree with your application’s terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this <em>acceptance</em> does not need to be recorded anywhere in your database (if you don’t have a field for it, the helper will just create a virtual attribute).</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"><</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 it.</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"><</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">=></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">3.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"><</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">Pay attention not to 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 the errors for each failed validation in the associated objects will be set there and not in this model.</p></div>
<h3 id="_the_tt_validates_confirmation_of_tt_helper">3.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, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with <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"><</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">
<pre><tt><%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %></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’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"><</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’t match confirmation</em>"</p></div>
<h3 id="_the_tt_validates_exclusion_of_tt_helper">3.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"><</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">=></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">=></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’d like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute’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">3.5. The <tt>validates_format_of</tt> helper</h3>
<div class="paragraph"><p>This helper validates the attributes’s values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the <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"><</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">=></span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span>
<span style="color: #990000">:</span>message <span style="color: #990000">=></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">3.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"><</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">=></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">=></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’d like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute’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">3.7. The <tt>validates_length_of</tt> helper</h3>
<div class="paragraph"><p>This helper validates the length of your attribute’s value. It can receive a variety of different options, so you can specify length contraints in different ways.</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"><</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">=></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">=></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">=></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">=></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 contraint 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"><</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">=></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>This helper has an alias called <tt>validates_size_of</tt>, it’s the same helper with a different name. You can use it if you’d like to.</p></div>
<h3 id="_the_tt_validates_numericality_of_tt_helper">3.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 use <tt>:integer_only</tt> set to <tt>true</tt>, then it will use the <tt>/\A[+\-]?\d+\Z/+ regular expression to validate the attribute’s value. Otherwise, it will try to convert the value 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"><</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>integer_only <span style="color: #990000">=></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>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">3.9. The <tt>validates_presence_of</tt> helper</h3>
<div class="paragraph"><p>This helper validates that the 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"><</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’ll need to test if 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"><</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 will want to use validates_inclusion_of :field_name, :in ⇒ [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # ⇒ true</td>
</tr></table>
</div>
<div class="paragraph"><p>The default error message for <tt>validates_presence_of</tt> is "<em>can’t be empty</em>".</p></div>
<h3 id="_the_tt_validates_uniqueness_of_tt_helper">3.10. The <tt>validates_uniqueness_of</tt> helper</h3>
<div class="paragraph"><p>This helper validates that the attribute’s value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.</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"><</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’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 must be used to define uniqueness:</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"><</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">=></span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span>
<span style="color: #990000">:</span>message <span style="color: #990000">=></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 if the uniqueness contraint 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"><</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">=></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">3.11. The <tt>validates_each</tt> helper</h3>
<div class="paragraph"><p>This helper validates attributes against a block. It doesn’t have a predefined validation function. You should create one using a block, and every attribute passed to <tt>validates_each</tt> will be tested against it. In the following example, we don’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"><</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’s name and the attribute’s value. 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">4. 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 we’ll cover right at the next topic.</p></div>
<h3 id="_the_tt_allow_nil_tt_option">4.1. The <tt>:allow_nil</tt> option</h3>
<div class="paragraph"><p>You may use the <tt>:allow_nil</tt> option everytime you want to trigger a validation only if the value being validated is not <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, 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"><</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">=></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">=></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">=></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">4.2. The <tt>:allow_blank</tt> option</h3>
<div class="paragraph"><p>In compliment to <tt>:allow_nil</tt> we have <tt>:allow_blank</tt>. This option will let validation pass if the attribute’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"><</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">=></span> <span style="color: #993399">5</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>allow_blank <span style="color: #990000">=></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">=></span> <span style="color: #FF0000">""</span><span style="color: #990000">).</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># => 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">=></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"># => true</span></span></tt></pre></div></div>
<h3 id="_the_tt_message_tt_option">4.3. The <tt>:message</tt> option</h3>
<div class="paragraph"><p>As stated before, 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.</p></div>
<h3 id="_the_tt_on_tt_option">4.4. The <tt>:on</tt> option</h3>
<div class="paragraph"><p>As stated before, the <tt>:on</tt> option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you’re creating a new record and when you’re updating it). If you want to change it, you can use <tt>:on => :create</tt> to run the validation only when a new record is created or <tt>:on => :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"><</span> ActiveRecord<span style="color: #990000">::</span>Base
<span style="font-style: italic"><span style="color: #9A1900"># => 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">=></span> <span style="color: #990000">:</span>create
<span style="font-style: italic"><span style="color: #9A1900"># => 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">=></span> <span style="color: #990000">:</span>update
<span style="font-style: italic"><span style="color: #9A1900"># => the default</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">=></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">5. 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">5.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"><</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">=></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">5.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"><</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">=></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">5.3. Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</h3>
<div class="paragraph"><p>Finally, it’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"><</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">=></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">6. 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"><</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"><</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"><=</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">=></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">=></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">=></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’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"><</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">7. 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’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’s state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of it’s attributes. <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"><</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"><</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"><</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">=></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"># => 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"><</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">=></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">=></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"># => 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"># => 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">=></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"># => 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"># => "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"># => 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"># => ["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’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"><</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">=></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"># => 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"># => ["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"># => true</span></span>
p<span style="color: #990000">.</span>save <span style="font-style: italic"><span style="color: #9A1900"># => 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"># => ["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">8. 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. It may be useful to display those messages when you’re trying to create or edit a record and validation fails. If you’re using the <tt>form_for</tt> helper to create a form, you can use it to call the <tt>error_messages</tt> method, which creates a <tt>div</tt> element containing all the error messages for the model associated with the form. Here is a simple example, using a <tt>Product</tt> model and the view template generated with the scaffold script.</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"><</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">=></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><% form_for(@product) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :description %><br />
<%= f.text_field :description %>
</p>
<p>
<%= f.label :value %><br />
<%= f.text_field :value %>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %></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’s very similar to the previous example and will achieve exactly the same result.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt><%= error_messages_for :product %></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><%= f.error_messages :header_message => "Invalid product!",
:message => "You'll need to fix the following fields:",
:header_tag => :h3 %></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’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’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">8.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"><span class='validation-error'></span><span style="color: #990000">&</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"></span></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"><span class='validation-error'></span><span style="color: #990000">&</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"></span></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">9. Callbacks</h2>
<div class="sectionbody">
<div class="paragraph"><p>Callbacks are methods that get called at certain moments of an object’s lifecycle. With callbacks it’s possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database.</p></div>
<h3 id="_callbacks_registration">9.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"><</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"><</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">10. 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">10.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’t be executed. This is the most common option. Using this form of registration it’s also possible to register several different methods that should be called to check the if the callback should be executed.</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"><</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">=></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">10.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"><</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">=></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">10.3. Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</h3>
<div class="paragraph"><p>Finally, it’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"><</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">=></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">10.4. Multiple Conditions for Callbacks</h3>
<div class="paragraph"><p>When writing conditional callbacks, it’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"><</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">=></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">=></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">11. 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">11.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">11.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">11.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">11.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">11.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">12. 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’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, 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.</p></div>
</div>
<h2 id="_callback_classes">13. Callback classes</h2>
<div class="sectionbody">
<div class="paragraph"><p>Sometimes the callback methods that you’ll write will be useful enough to be reused at other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.</p></div>
<div class="paragraph"><p>Here’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"><</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’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"><</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">14. 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’s not directly related to the model’s purpose. In object-oriented software, it’s always a good idea to design your classes with a single responsibility in the whole system. For example, it wouldn’t make much sense to have a <tt>User</tt> model with a method that writes data about a login attempt to a log file. Whenever you’re using callbacks to write code that’s not directly related to your model class purposes, it may be a good moment to create an Observer.</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’s implementation remains clean, while you can reuse the code in the Observer to add behaviour to more than one model class. OK, you may say that we can also do that using callback classes, but it would still force us to add code to our model’s implementation.</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’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"><</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’s methods receive the observed model as a parameter.</p></div>
<div class="paragraph"><p>Sometimes using the ModelName + Observer naming convention won’t be the best choice, mainly when you want to use the same observer for more than one model class. It’s possible to explicity specify the models that our observer should observe.</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"><</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">14.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’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’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">14.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">15. Changelog</h2>
<div class="sectionbody">
<div class="paragraph"><p><a href="http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks">http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks</a></p></div>
</div>
</div>
</div>
</body>
</html>
|