Froze rails gems
[depot.git] / vendor / rails / railties / doc / guides / html / activerecord_validations_callbacks.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
5 <title>Active Record Validations and Callbacks</title>
6 <!--[if lt IE 8]>
7 <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
8 <![endif]-->
9 <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
10 <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
11 <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
12 <style type="text/css">
13 div#container {
14 max-width: 900px;
15 padding-bottom: 3em;
16 }
17
18 div#content {
19 margin-left: 200px;
20 }
21
22 div#container.notoc {
23 max-width: 600px;
24 }
25
26 .notoc div#content {
27 margin-left: 0;
28 }
29
30 pre {
31 line-height: 1.4em;
32 }
33
34 #content p tt {
35 background: #eeeeee;
36 border: solid 1px #cccccc;
37 padding: 3px;
38 }
39
40 dt {
41 font-weight: bold;
42 }
43
44 #content dt tt {
45 font-size: 10pt;
46 }
47
48 dd {
49 margin-left: 3em;
50 }
51
52 #content dt tt, #content pre tt {
53 background: none;
54 padding: 0;
55 border: 0;
56 }
57
58 #content .olist ol {
59 margin-left: 2em;
60 }
61
62 #header {
63 position: relative;
64 max-width: 840px;
65 margin-left: auto;
66 margin-right: auto;
67 }
68
69 #header.notoc {
70 max-width: 580px;
71 }
72
73 #logo {
74 position: absolute;
75 left: 10px;
76 top: 10px;
77 width: 110px;
78 height: 140px;
79 }
80
81 div#header h1#site_title {
82 background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
83 position: absolute;
84 width: 392px;
85 height: 55px;
86 left: 145px;
87 top: 20px;
88 margin: 0;
89 padding: 0;
90 }
91
92 #site_title span {
93 display: none;
94 }
95
96 #site_title_tagline {
97 display: none;
98 }
99
100 ul#navMain {
101 position: absolute;
102 margin: 0;
103 padding: 0;
104 top: 97px;
105 left: 145px;
106 }
107
108 .left-floaty, .right-floaty {
109 padding: 15px;
110 }
111
112 .admonitionblock,
113 .tableblock {
114 margin-left: 1em;
115 margin-right: 1em;
116 margin-top: 0.25em;
117 margin-bottom: 1em;
118 }
119
120 .admonitionblock .icon {
121 padding-right: 8px;
122 }
123
124 .admonitionblock .content {
125 border: solid 1px #ffda78;
126 background: #fffebd;
127 padding: 10px;
128 padding-top: 8px;
129 padding-bottom: 8px;
130 }
131
132 .admonitionblock .title {
133 font-size: 140%;
134 margin-bottom: 0.5em;
135 }
136
137 .tableblock table {
138 border: solid 1px #aaaaff;
139 background: #f0f0ff;
140 }
141
142 .tableblock th {
143 background: #e0e0e0;
144 }
145
146 .tableblock th,
147 .tableblock td {
148 padding: 3px;
149 padding-left: 5px;
150 padding-right: 5px;
151 }
152
153 .sidebarblock {
154 margin-top: 0.25em;
155 margin: 1em;
156 border: solid 1px #ccccbb;
157 padding: 8px;
158 background: #ffffe0;
159 }
160
161 .sidebarblock .sidebar-title {
162 font-size: 140%;
163 font-weight: 600;
164 margin-bottom: 0.3em;
165 }
166
167 .sidebarblock .sidebar-content > .para:last-child > p {
168 margin-bottom: 0;
169 }
170
171 .sidebarblock .sidebar-title a {
172 text-decoration: none;
173 }
174
175 .sidebarblock .sidebar-title a:hover {
176 text-decoration: underline;
177 }
178
179 </style>
180 </head>
181 <body>
182 <div id="header" >
183 <div id="logo">
184 <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
185 </div>
186
187 <h1 id="site_title"><span>Ruby on Rails</span></h1>
188 <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>
189
190 <ul id="navMain">
191 <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
192 <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
193 </ul>
194 </div>
195
196 <div id="container">
197
198 <div id="sidebar">
199 <h2>Chapters</h2>
200 <ol>
201 <li>
202 <a href="#_motivations_to_validate_your_active_record_objects">Motivations to validate your Active Record objects</a>
203 </li>
204 <li>
205 <a href="#_how_it_works">How it works</a>
206 <ul>
207
208 <li><a href="#_when_does_validation_happens">When does validation happens?</a></li>
209
210 <li><a href="#_the_meaning_of_em_valid_em">The meaning of <em>valid</em></a></li>
211
212 </ul>
213 </li>
214 <li>
215 <a href="#_the_declarative_validation_helpers">The declarative validation helpers</a>
216 <ul>
217
218 <li><a href="#_the_tt_validates_acceptance_of_tt_helper">The <tt>validates_acceptance_of</tt> helper</a></li>
219
220 <li><a href="#_the_tt_validates_associated_tt_helper">The <tt>validates_associated</tt> helper</a></li>
221
222 <li><a href="#_the_tt_validates_confirmation_of_tt_helper">The <tt>validates_confirmation_of</tt> helper</a></li>
223
224 <li><a href="#_the_tt_validates_each_tt_helper">The <tt>validates_each</tt> helper</a></li>
225
226 <li><a href="#_the_tt_validates_exclusion_of_tt_helper">The <tt>validates_exclusion_of</tt> helper</a></li>
227
228 <li><a href="#_the_tt_validates_format_of_tt_helper">The <tt>validates_format_of</tt> helper</a></li>
229
230 <li><a href="#_the_tt_validates_inclusion_of_tt_helper">The <tt>validates_inclusion_of</tt> helper</a></li>
231
232 <li><a href="#_the_tt_validates_length_of_tt_helper">The <tt>validates_length_of</tt> helper</a></li>
233
234 <li><a href="#_the_tt_validates_numericallity_of_tt_helper">The <tt>validates_numericallity_of</tt> helper</a></li>
235
236 <li><a href="#_the_tt_validates_presence_of_tt_helper">The <tt>validates_presence_of</tt> helper</a></li>
237
238 <li><a href="#_the_tt_validates_uniqueness_of_tt_helper">The <tt>validates_uniqueness_of</tt> helper</a></li>
239
240 </ul>
241 </li>
242 <li>
243 <a href="#_common_validation_options">Common validation options</a>
244 <ul>
245
246 <li><a href="#_the_tt_allow_nil_tt_option">The <tt>:allow_nil</tt> option</a></li>
247
248 <li><a href="#_the_tt_message_tt_option">The <tt>:message</tt> option</a></li>
249
250 <li><a href="#_the_tt_on_tt_option">The <tt>:on</tt> option</a></li>
251
252 </ul>
253 </li>
254 <li>
255 <a href="#_conditional_validation">Conditional validation</a>
256 <ul>
257
258 <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>
259
260 <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>
261
262 <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>
263
264 </ul>
265 </li>
266 <li>
267 <a href="#_writing_your_own_validation_methods">Writing your own validation methods</a>
268 </li>
269 <li>
270 <a href="#_changelog">Changelog</a>
271 </li>
272 </ol>
273 </div>
274
275 <div id="content">
276 <h1>Active Record Validations and Callbacks</h1>
277 <div id="preamble">
278 <div class="sectionbody">
279 <div class="para"><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>
280 <div class="para"><p>After reading this guide and trying out the presented concepts, we hope that you'll be able to:</p></div>
281 <div class="ilist"><ul>
282 <li>
283 <p>
284 Correctly use all the built-in Active Record validation helpers
285 </p>
286 </li>
287 <li>
288 <p>
289 Create your own custom validation methods
290 </p>
291 </li>
292 <li>
293 <p>
294 Work with the error messages generated by the validation proccess
295 </p>
296 </li>
297 <li>
298 <p>
299 Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved.
300 </p>
301 </li>
302 <li>
303 <p>
304 Create special classes that encapsulate common behaviour for your callbacks
305 </p>
306 </li>
307 <li>
308 <p>
309 Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
310 </p>
311 </li>
312 </ul></div>
313 </div>
314 </div>
315 <h2 id="_motivations_to_validate_your_active_record_objects">1. Motivations to validate your Active Record objects</h2>
316 <div class="sectionbody">
317 <div class="para"><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>
318 <div class="para"><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>
319 <div class="ilist"><ul>
320 <li>
321 <p>
322 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.
323 </p>
324 </li>
325 <li>
326 <p>
327 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.
328 </p>
329 </li>
330 <li>
331 <p>
332 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.
333 </p>
334 </li>
335 </ul></div>
336 </div>
337 <h2 id="_how_it_works">2. How it works</h2>
338 <div class="sectionbody">
339 <h3 id="_when_does_validation_happens">2.1. When does validation happens?</h3>
340 <div class="para"><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>
341 <div class="listingblock">
342 <div class="content"><!-- Generator: GNU source-highlight 2.9
343 by Lorenzo Bettini
344 http://www.lorenzobettini.it
345 http://www.gnu.org/software/src-highlite -->
346 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
347 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
348 </tt></pre></div></div>
349 <div class="para"><p>We can see how it works by looking at the following script/console output:</p></div>
350 <div class="listingblock">
351 <div class="content">
352 <pre><tt>&gt;&gt; p = Person.new(:name =&gt; "John Doe", :birthdate =&gt; Date.parse("09/03/1979"))
353 =&gt; #&lt;Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil&gt;
354 &gt;&gt; p.new_record?
355 =&gt; true
356 &gt;&gt; p.save
357 =&gt; true
358 &gt;&gt; p.new_record?
359 =&gt; false</tt></pre>
360 </div></div>
361 <div class="para"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt>, <tt>update_attribute</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.</p></div>
362 <h3 id="_the_meaning_of_em_valid_em">2.2. The meaning of <em>valid</em></h3>
363 <div class="para"><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>
364 </div>
365 <h2 id="_the_declarative_validation_helpers">3. The declarative validation helpers</h2>
366 <div class="sectionbody">
367 <div class="para"><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>
368 <div class="para"><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>
369 <div class="para"><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 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>
370 <h3 id="_the_tt_validates_acceptance_of_tt_helper">3.1. The <tt>validates_acceptance_of</tt> helper</h3>
371 <div class="para"><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>
372 <div class="listingblock">
373 <div class="content"><!-- Generator: GNU source-highlight 2.9
374 by Lorenzo Bettini
375 http://www.lorenzobettini.it
376 http://www.gnu.org/software/src-highlite -->
377 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
378 validates_acceptance_of <span style="color: #990000">:</span>terms_of_service
379 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
380 </tt></pre></div></div>
381 <div class="para"><p>The default error message for <tt>validates_acceptance_of</tt> is "<em>must be accepted</em>"</p></div>
382 <div class="para"><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>
383 <div class="listingblock">
384 <div class="content"><!-- Generator: GNU source-highlight 2.9
385 by Lorenzo Bettini
386 http://www.lorenzobettini.it
387 http://www.gnu.org/software/src-highlite -->
388 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
389 validates_acceptance_of <span style="color: #990000">:</span>terms_of_service<span style="color: #990000">,</span> <span style="color: #990000">:</span>accept <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'yes'</span>
390 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
391 </tt></pre></div></div>
392 <h3 id="_the_tt_validates_associated_tt_helper">3.2. The <tt>validates_associated</tt> helper</h3>
393 <div class="para"><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>
394 <div class="listingblock">
395 <div class="content"><!-- Generator: GNU source-highlight 2.9
396 by Lorenzo Bettini
397 http://www.lorenzobettini.it
398 http://www.gnu.org/software/src-highlite -->
399 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Library <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
400 has_many <span style="color: #990000">:</span>books
401 validates_associated <span style="color: #990000">:</span>books
402 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
403 </tt></pre></div></div>
404 <div class="para"><p>This validation will work with all the association types.</p></div>
405 <div class="admonitionblock">
406 <table><tr>
407 <td class="icon">
408 <img src="./images/icons/caution.png" alt="Caution" />
409 </td>
410 <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>
411 </tr></table>
412 </div>
413 <div class="para"><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>
414 <h3 id="_the_tt_validates_confirmation_of_tt_helper">3.3. The <tt>validates_confirmation_of</tt> helper</h3>
415 <div class="para"><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>
416 <div class="listingblock">
417 <div class="content"><!-- Generator: GNU source-highlight 2.9
418 by Lorenzo Bettini
419 http://www.lorenzobettini.it
420 http://www.gnu.org/software/src-highlite -->
421 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
422 validates_confirmation_of <span style="color: #990000">:</span>email
423 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
424 </tt></pre></div></div>
425 <div class="para"><p>In your view template you could use something like</p></div>
426 <div class="listingblock">
427 <div class="content">
428 <pre><tt>&lt;%= text_field :person, :email %&gt;
429 &lt;%= text_field :person, :email_confirmation %&gt;</tt></pre>
430 </div></div>
431 <div class="admonitionblock">
432 <table><tr>
433 <td class="icon">
434 <img src="./images/icons/note.png" alt="Note" />
435 </td>
436 <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>
437 </tr></table>
438 </div>
439 <div class="listingblock">
440 <div class="content"><!-- Generator: GNU source-highlight 2.9
441 by Lorenzo Bettini
442 http://www.lorenzobettini.it
443 http://www.gnu.org/software/src-highlite -->
444 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
445 validates_confirmation_of <span style="color: #990000">:</span>email
446 validates_presence_of <span style="color: #990000">:</span>email_confirmation
447 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
448 </tt></pre></div></div>
449 <div class="para"><p>The default error message for <tt>validates_confirmation_of</tt> is "<em>doesn't match confirmation</em>"</p></div>
450 <h3 id="_the_tt_validates_each_tt_helper">3.4. The <tt>validates_each</tt> helper</h3>
451 <div class="para"><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>
452 <div class="listingblock">
453 <div class="content"><!-- Generator: GNU source-highlight 2.9
454 by Lorenzo Bettini
455 http://www.lorenzobettini.it
456 http://www.gnu.org/software/src-highlite -->
457 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
458 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>
459 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>
460 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
461 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
462 </tt></pre></div></div>
463 <div class="para"><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>
464 <h3 id="_the_tt_validates_exclusion_of_tt_helper">3.5. The <tt>validates_exclusion_of</tt> helper</h3>
465 <div class="para"><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>
466 <div class="listingblock">
467 <div class="content"><!-- Generator: GNU source-highlight 2.9
468 by Lorenzo Bettini
469 http://www.lorenzobettini.it
470 http://www.gnu.org/software/src-highlite -->
471 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> MovieFile <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
472 validates_exclusion_of <span style="color: #990000">:</span>format<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>mov avi<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Extension %s is not allowed"</span>
473 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
474 </tt></pre></div></div>
475 <div class="para"><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>
476 <div class="para"><p>The default error message for <tt>validates_exclusion_of</tt> is "<em>is not included in the list</em>".</p></div>
477 <h3 id="_the_tt_validates_format_of_tt_helper">3.6. The <tt>validates_format_of</tt> helper</h3>
478 <div class="para"><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>
479 <div class="listingblock">
480 <div class="content"><!-- Generator: GNU source-highlight 2.9
481 by Lorenzo Bettini
482 http://www.lorenzobettini.it
483 http://www.gnu.org/software/src-highlite -->
484 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
485 validates_format_of <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Only letters allowed"</span>
486 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
487 </tt></pre></div></div>
488 <div class="para"><p>The default error message for <tt>validates_format_of</tt> is "<em>is invalid</em>".</p></div>
489 <h3 id="_the_tt_validates_inclusion_of_tt_helper">3.7. The <tt>validates_inclusion_of</tt> helper</h3>
490 <div class="para"><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>
491 <div class="listingblock">
492 <div class="content"><!-- Generator: GNU source-highlight 2.9
493 by Lorenzo Bettini
494 http://www.lorenzobettini.it
495 http://www.gnu.org/software/src-highlite -->
496 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
497 validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span>
498 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
499 </tt></pre></div></div>
500 <div class="para"><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>
501 <div class="para"><p>The default error message for <tt>validates_inclusion_of</tt> is "<em>is not included in the list</em>".</p></div>
502 <h3 id="_the_tt_validates_length_of_tt_helper">3.8. The <tt>validates_length_of</tt> helper</h3>
503 <div class="para"><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>
504 <div class="listingblock">
505 <div class="content"><!-- Generator: GNU source-highlight 2.9
506 by Lorenzo Bettini
507 http://www.lorenzobettini.it
508 http://www.gnu.org/software/src-highlite -->
509 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
510 validates_length_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>minimum <span style="color: #990000">=&gt;</span> <span style="color: #993399">2</span>
511 validates_length_of <span style="color: #990000">:</span>bio<span style="color: #990000">,</span> <span style="color: #990000">:</span>maximum <span style="color: #990000">=&gt;</span> <span style="color: #993399">500</span>
512 validates_length_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #993399">6</span><span style="color: #990000">..</span><span style="color: #993399">20</span>
513 validates_length_of <span style="color: #990000">:</span>registration_number<span style="color: #990000">,</span> <span style="color: #990000">:</span>is <span style="color: #990000">=&gt;</span> <span style="color: #993399">6</span>
514 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
515 </tt></pre></div></div>
516 <div class="para"><p>The possible length constraint options are:</p></div>
517 <div class="ilist"><ul>
518 <li>
519 <p>
520 <tt>:minimum</tt> - The attribute cannot have less than the specified length.
521 </p>
522 </li>
523 <li>
524 <p>
525 <tt>:maximum</tt> - The attribute cannot have more than the specified length.
526 </p>
527 </li>
528 <li>
529 <p>
530 <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.
531 </p>
532 </li>
533 <li>
534 <p>
535 <tt>:is</tt> - The attribute length must be equal to a given value.
536 </p>
537 </li>
538 </ul></div>
539 <div class="para"><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>
540 <div class="listingblock">
541 <div class="content"><!-- Generator: GNU source-highlight 2.9
542 by Lorenzo Bettini
543 http://www.lorenzobettini.it
544 http://www.gnu.org/software/src-highlite -->
545 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
546 validates_length_of <span style="color: #990000">:</span>bio<span style="color: #990000">,</span> <span style="color: #990000">:</span>too_long <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"you're writing too much. %d characters is the maximum allowed."</span>
547 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
548 </tt></pre></div></div>
549 <div class="para"><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>
550 <h3 id="_the_tt_validates_numericallity_of_tt_helper">3.9. The <tt>validates_numericallity_of</tt> helper</h3>
551 <div class="para"><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>
552 <div class="para"><p>If you use <tt>:integer_only</tt> set to <tt>true</tt>, then it will use the <tt><span>/\A[+\-]?\d+\Z/</span></tt> regular expression to validate the attribute's value. Otherwise, it will try to convert the value using <tt>Kernel.Float</tt>.</p></div>
553 <div class="listingblock">
554 <div class="content"><!-- Generator: GNU source-highlight 2.9
555 by Lorenzo Bettini
556 http://www.lorenzobettini.it
557 http://www.gnu.org/software/src-highlite -->
558 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Player <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
559 validates_numericallity_of <span style="color: #990000">:</span>points
560 validates_numericallity_of <span style="color: #990000">:</span>games_played<span style="color: #990000">,</span> <span style="color: #990000">:</span>integer_only <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
561 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
562 </tt></pre></div></div>
563 <div class="para"><p>The default error message for <tt>validates_numericallity_of</tt> is "<em>is not a number</em>".</p></div>
564 <h3 id="_the_tt_validates_presence_of_tt_helper">3.10. The <tt>validates_presence_of</tt> helper</h3>
565 <div class="para"><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>
566 <div class="listingblock">
567 <div class="content"><!-- Generator: GNU source-highlight 2.9
568 by Lorenzo Bettini
569 http://www.lorenzobettini.it
570 http://www.gnu.org/software/src-highlite -->
571 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
572 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
573 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
574 </tt></pre></div></div>
575 <div class="admonitionblock">
576 <table><tr>
577 <td class="icon">
578 <img src="./images/icons/note.png" alt="Note" />
579 </td>
580 <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>
581 </tr></table>
582 </div>
583 <div class="listingblock">
584 <div class="content"><!-- Generator: GNU source-highlight 2.9
585 by Lorenzo Bettini
586 http://www.lorenzobettini.it
587 http://www.gnu.org/software/src-highlite -->
588 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
589 belongs_to <span style="color: #990000">:</span>order
590 validates_presence_of <span style="color: #990000">:</span>order_id
591 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
592 </tt></pre></div></div>
593 <div class="admonitionblock">
594 <table><tr>
595 <td class="icon">
596 <img src="./images/icons/note.png" alt="Note" />
597 </td>
598 <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 &#8658; [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # &#8658; true</td>
599 </tr></table>
600 </div>
601 <div class="para"><p>The default error message for <tt>validates_presence_of</tt> is "<em>can't be empty</em>".</p></div>
602 <h3 id="_the_tt_validates_uniqueness_of_tt_helper">3.11. The <tt>validates_uniqueness_of</tt> helper</h3>
603 <div class="para"><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>
604 <div class="listingblock">
605 <div class="content"><!-- Generator: GNU source-highlight 2.9
606 by Lorenzo Bettini
607 http://www.lorenzobettini.it
608 http://www.gnu.org/software/src-highlite -->
609 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
610 validates_uniqueness_of <span style="color: #990000">:</span>email
611 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
612 </tt></pre></div></div>
613 <div class="para"><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>
614 <div class="para"><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>
615 <div class="listingblock">
616 <div class="content"><!-- Generator: GNU source-highlight 2.9
617 by Lorenzo Bettini
618 http://www.lorenzobettini.it
619 http://www.gnu.org/software/src-highlite -->
620 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Holiday <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
621 validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Should happen once per year"</span>
622 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
623 </tt></pre></div></div>
624 <div class="para"><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>
625 <div class="listingblock">
626 <div class="content"><!-- Generator: GNU source-highlight 2.9
627 by Lorenzo Bettini
628 http://www.lorenzobettini.it
629 http://www.gnu.org/software/src-highlite -->
630 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
631 validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>case_sensitive <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
632 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
633 </tt></pre></div></div>
634 <div class="para"><p>The default error message for <tt>validates_uniqueness_of</tt> is "<em>has already been taken</em>".</p></div>
635 </div>
636 <h2 id="_common_validation_options">4. Common validation options</h2>
637 <div class="sectionbody">
638 <div class="para"><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>
639 <h3 id="_the_tt_allow_nil_tt_option">4.1. The <tt>:allow_nil</tt> option</h3>
640 <div class="para"><p>You may use the <tt>:allow_nil</tt> option everytime you just want to trigger a validation 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>
641 <div class="listingblock">
642 <div class="content"><!-- Generator: GNU source-highlight 2.9
643 by Lorenzo Bettini
644 http://www.lorenzobettini.it
645 http://www.gnu.org/software/src-highlite -->
646 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
647 validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span>
648 <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>allow_nil <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
649 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
650 </tt></pre></div></div>
651 <h3 id="_the_tt_message_tt_option">4.2. The <tt>:message</tt> option</h3>
652 <div class="para"><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>
653 <h3 id="_the_tt_on_tt_option">4.3. The <tt>:on</tt> option</h3>
654 <div class="para"><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 =<span>&gt;</span> :create</tt> to run the validation only when a new record is created or <tt>:on =<span>&gt;</span> :update</tt> to run the validation only when a record is updated.</p></div>
655 <div class="listingblock">
656 <div class="content"><!-- Generator: GNU source-highlight 2.9
657 by Lorenzo Bettini
658 http://www.lorenzobettini.it
659 http://www.gnu.org/software/src-highlite -->
660 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
661 validates_uniqueness_of <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to update email with a duplicated value</span></span>
662 validates_numericallity_of <span style="color: #990000">:</span>age<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>update <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to create the record with a 'non-numerical age'</span></span>
663 validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>save <span style="font-style: italic"><span style="color: #9A1900"># =&gt; that's the default</span></span>
664 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
665 </tt></pre></div></div>
666 </div>
667 <h2 id="_conditional_validation">5. Conditional validation</h2>
668 <div class="sectionbody">
669 <div class="para"><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>
670 <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>
671 <div class="para"><p>You can associated 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>
672 <div class="listingblock">
673 <div class="content"><!-- Generator: GNU source-highlight 2.9
674 by Lorenzo Bettini
675 http://www.lorenzobettini.it
676 http://www.gnu.org/software/src-highlite -->
677 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
678 validates_presence_of <span style="color: #990000">:</span>card_number<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>paid_with_card?
679
680 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> paid_with_card?
681 payment_type <span style="color: #990000">==</span> <span style="color: #FF0000">"card"</span>
682 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
683 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
684 </tt></pre></div></div>
685 <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>
686 <div class="para"><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>
687 <div class="listingblock">
688 <div class="content"><!-- Generator: GNU source-highlight 2.9
689 by Lorenzo Bettini
690 http://www.lorenzobettini.it
691 http://www.gnu.org/software/src-highlite -->
692 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
693 validates_presence_of <span style="color: #990000">:</span>surname<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"name.nil?"</span>
694 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
695 </tt></pre></div></div>
696 <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>
697 <div class="para"><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>
698 <div class="listingblock">
699 <div class="content"><!-- Generator: GNU source-highlight 2.9
700 by Lorenzo Bettini
701 http://www.lorenzobettini.it
702 http://www.gnu.org/software/src-highlite -->
703 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
704 validates_confirmation_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>a<span style="color: #990000">|</span> a<span style="color: #990000">.</span>password<span style="color: #990000">.</span>blank? <span style="color: #FF0000">}</span>
705 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
706 </tt></pre></div></div>
707 </div>
708 <h2 id="_writing_your_own_validation_methods">6. Writing your own validation methods</h2>
709 <div class="sectionbody">
710 <div class="para"><p>When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's <tt>errors</tt> collection.</p></div>
711 <div class="listingblock">
712 <div class="content"><!-- Generator: GNU source-highlight 2.9
713 by Lorenzo Bettini
714 http://www.lorenzobettini.it
715 http://www.gnu.org/software/src-highlite -->
716 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
717 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> validate_on_create
718 errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
719 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
720 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
721 </tt></pre></div></div>
722 <div class="para"><p>If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods, passing it the symbols for the methods' names.</p></div>
723 <div class="listingblock">
724 <div class="content"><!-- Generator: GNU source-highlight 2.9
725 by Lorenzo Bettini
726 http://www.lorenzobettini.it
727 http://www.gnu.org/software/src-highlite -->
728 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
729 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
730
731 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> expiration_date_cannot_be_in_the_past
732 errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
733 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
734
735 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> discount_cannot_be_greater_than_total_value
736 errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>discount<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be greater than total value"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> discount <span style="color: #990000">&lt;=</span> total_value
737 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
738 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
739 </tt></pre></div></div>
740 </div>
741 <h2 id="_changelog">7. Changelog</h2>
742 <div class="sectionbody">
743 <div class="para"><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>
744 </div>
745
746 </div>
747 </div>
748 </body>
749 </html>