railties 3.1.1 → 3.1.2.rc1
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG.md +2382 -0
- data/guides/output/2_2_release_notes.html +565 -0
- data/guides/output/2_3_release_notes.html +713 -0
- data/guides/output/3_0_release_notes.html +652 -0
- data/guides/output/3_1_release_notes.html +670 -0
- data/guides/output/action_controller_overview.html +925 -0
- data/guides/output/action_mailer_basics.html +658 -0
- data/guides/output/action_view_overview.html +1471 -0
- data/guides/output/active_model_basics.html +349 -0
- data/guides/output/active_record_basics.html +364 -0
- data/guides/output/active_record_querying.html +1272 -0
- data/guides/output/active_record_validations_callbacks.html +1292 -0
- data/guides/output/active_resource_basics.html +252 -0
- data/guides/output/active_support_core_extensions.html +3374 -0
- data/guides/output/ajax_on_rails.html +412 -0
- data/guides/output/api_documentation_guidelines.html +317 -0
- data/guides/output/asset_pipeline.html +691 -0
- data/guides/output/association_basics.html +1742 -0
- data/guides/output/caching_with_rails.html +533 -0
- data/guides/output/command_line.html +662 -0
- data/guides/output/configuring.html +811 -0
- data/guides/output/contribute.html +216 -0
- data/guides/output/contributing_to_ruby_on_rails.html +465 -0
- data/guides/output/credits.html +210 -0
- data/guides/output/debugging_rails_applications.html +791 -0
- data/guides/output/engines.html +673 -0
- data/guides/output/form_helpers.html +850 -0
- data/guides/output/generators.html +725 -0
- data/guides/output/getting_started.html +1980 -0
- data/guides/output/i18n.html +1054 -0
- data/guides/output/images/belongs_to.png +0 -0
- data/guides/output/images/book_icon.gif +0 -0
- data/guides/output/images/bullet.gif +0 -0
- data/guides/output/images/challenge.png +0 -0
- data/guides/output/images/chapters_icon.gif +0 -0
- data/guides/output/images/check_bullet.gif +0 -0
- data/guides/output/images/credits_pic_blank.gif +0 -0
- data/guides/output/images/csrf.png +0 -0
- data/guides/output/images/customized_error_messages.png +0 -0
- data/guides/output/images/edge_badge.png +0 -0
- data/guides/output/images/error_messages.png +0 -0
- data/guides/output/images/feature_tile.gif +0 -0
- data/guides/output/images/footer_tile.gif +0 -0
- data/guides/output/images/fxn.png +0 -0
- data/guides/output/images/grey_bullet.gif +0 -0
- data/guides/output/images/habtm.png +0 -0
- data/guides/output/images/has_many.png +0 -0
- data/guides/output/images/has_many_through.png +0 -0
- data/guides/output/images/has_one.png +0 -0
- data/guides/output/images/has_one_through.png +0 -0
- data/guides/output/images/header_backdrop.png +0 -0
- data/guides/output/images/header_tile.gif +0 -0
- data/guides/output/images/i18n/demo_html_safe.png +0 -0
- data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translated_en.png +0 -0
- data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translation_missing.png +0 -0
- data/guides/output/images/i18n/demo_untranslated.png +0 -0
- data/guides/output/images/icons/README +5 -0
- data/guides/output/images/icons/callouts/1.png +0 -0
- data/guides/output/images/icons/callouts/10.png +0 -0
- data/guides/output/images/icons/callouts/11.png +0 -0
- data/guides/output/images/icons/callouts/12.png +0 -0
- data/guides/output/images/icons/callouts/13.png +0 -0
- data/guides/output/images/icons/callouts/14.png +0 -0
- data/guides/output/images/icons/callouts/15.png +0 -0
- data/guides/output/images/icons/callouts/2.png +0 -0
- data/guides/output/images/icons/callouts/3.png +0 -0
- data/guides/output/images/icons/callouts/4.png +0 -0
- data/guides/output/images/icons/callouts/5.png +0 -0
- data/guides/output/images/icons/callouts/6.png +0 -0
- data/guides/output/images/icons/callouts/7.png +0 -0
- data/guides/output/images/icons/callouts/8.png +0 -0
- data/guides/output/images/icons/callouts/9.png +0 -0
- data/guides/output/images/icons/caution.png +0 -0
- data/guides/output/images/icons/example.png +0 -0
- data/guides/output/images/icons/home.png +0 -0
- data/guides/output/images/icons/important.png +0 -0
- data/guides/output/images/icons/next.png +0 -0
- data/guides/output/images/icons/note.png +0 -0
- data/guides/output/images/icons/prev.png +0 -0
- data/guides/output/images/icons/tip.png +0 -0
- data/guides/output/images/icons/up.png +0 -0
- data/guides/output/images/icons/warning.png +0 -0
- data/guides/output/images/jaimeiniesta.jpg +0 -0
- data/guides/output/images/nav_arrow.gif +0 -0
- data/guides/output/images/polymorphic.png +0 -0
- data/guides/output/images/posts_index.png +0 -0
- data/guides/output/images/radar.png +0 -0
- data/guides/output/images/rails_guides_logo.gif +0 -0
- data/guides/output/images/rails_logo_remix.gif +0 -0
- data/guides/output/images/rails_welcome.png +0 -0
- data/guides/output/images/session_fixation.png +0 -0
- data/guides/output/images/tab_grey.gif +0 -0
- data/guides/output/images/tab_info.gif +0 -0
- data/guides/output/images/tab_note.gif +0 -0
- data/guides/output/images/tab_red.gif +0 -0
- data/guides/output/images/tab_yellow.gif +0 -0
- data/guides/output/images/tab_yellow.png +0 -0
- data/guides/output/images/validation_error_messages.png +0 -0
- data/guides/output/images/vijaydev.jpg +0 -0
- data/guides/output/index.html +300 -0
- data/guides/output/initialization.html +1087 -0
- data/guides/output/javascripts/guides.js +7 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
- data/guides/output/javascripts/syntaxhighlighter/shCore.js +17 -0
- data/guides/output/layout.html +312 -0
- data/guides/output/layouts_and_rendering.html +1257 -0
- data/guides/output/migrations.html +751 -0
- data/guides/output/nested_model_forms.html +350 -0
- data/guides/output/performance_testing.html +858 -0
- data/guides/output/plugins.html +590 -0
- data/guides/output/rails_application_templates.html +368 -0
- data/guides/output/rails_on_rack.html +408 -0
- data/guides/output/routing.html +1246 -0
- data/guides/output/ruby_on_rails_guides_guidelines.html +218 -0
- data/guides/output/security.html +968 -0
- data/guides/output/stylesheets/fixes.css +16 -0
- data/guides/output/stylesheets/main.css +445 -0
- data/guides/output/stylesheets/print.css +52 -0
- data/guides/output/stylesheets/reset.css +43 -0
- data/guides/output/stylesheets/style.css +13 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCore.css +226 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
- data/guides/output/testing.html +1182 -0
- data/guides/source/active_record_validations_callbacks.textile +3 -3
- data/guides/source/active_support_core_extensions.textile +2 -2
- data/guides/source/asset_pipeline.textile +7 -5
- data/guides/source/association_basics.textile +2 -4
- data/guides/source/command_line.textile +1 -1
- data/guides/source/configuring.textile +4 -2
- data/guides/source/contributing_to_ruby_on_rails.textile +6 -6
- data/guides/source/initialization.textile +2 -2
- data/guides/source/performance_testing.textile +1 -1
- data/guides/source/routing.textile +1 -1
- data/guides/source/security.textile +2 -2
- data/lib/rails/commands/server.rb +1 -1
- data/lib/rails/engine.rb +1 -1
- data/lib/rails/generators/app_base.rb +2 -1
- data/lib/rails/generators/base.rb +3 -3
- data/lib/rails/generators/rails/app/templates/gitignore +15 -5
- data/lib/rails/rack.rb +0 -1
- data/lib/rails/tasks/documentation.rake +7 -7
- data/lib/rails/tasks/misc.rake +0 -2
- data/lib/rails/test_unit/testing.rake +2 -0
- data/lib/rails/version.rb +2 -2
- metadata +495 -326
- data/CHANGELOG +0 -2371
- data/lib/rails/rack/content_length.rb +0 -38
@@ -0,0 +1,1292 @@
|
|
1
|
+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
2
|
+
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
3
|
+
|
4
|
+
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
5
|
+
<head>
|
6
|
+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
7
|
+
|
8
|
+
<title>Ruby on Rails Guides: Active Record Validations and Callbacks</title>
|
9
|
+
|
10
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
|
11
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
|
12
|
+
|
13
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
|
14
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
|
15
|
+
|
16
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
|
17
|
+
</head>
|
18
|
+
<body class="guide">
|
19
|
+
<div id="topNav">
|
20
|
+
<div class="wrapper">
|
21
|
+
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
|
22
|
+
<a href="http://rubyonrails.org/">Overview</a> |
|
23
|
+
<a href="http://rubyonrails.org/download">Download</a> |
|
24
|
+
<a href="http://rubyonrails.org/deploy">Deploy</a> |
|
25
|
+
<a href="https://github.com/rails/rails">Code</a> |
|
26
|
+
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
|
27
|
+
<a href="http://rubyonrails.org/documentation">Documentation</a> |
|
28
|
+
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
|
29
|
+
<a href="http://rubyonrails.org/community">Community</a> |
|
30
|
+
<a href="http://weblog.rubyonrails.org/">Blog</a>
|
31
|
+
</div>
|
32
|
+
</div>
|
33
|
+
<div id="header">
|
34
|
+
<div class="wrapper clearfix">
|
35
|
+
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
|
36
|
+
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
|
37
|
+
<ul class="nav">
|
38
|
+
<li><a href="index.html">Home</a></li>
|
39
|
+
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
|
40
|
+
<div id="guides" class="clearfix" style="display: none;">
|
41
|
+
<hr />
|
42
|
+
<dl class="L">
|
43
|
+
<dt>Start Here</dt>
|
44
|
+
<dd><a href="getting_started.html">Getting Started with Rails</a></dd>
|
45
|
+
<dt>Models</dt>
|
46
|
+
<dd><a href="migrations.html">Rails Database Migrations</a></dd>
|
47
|
+
<dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
|
48
|
+
<dd><a href="association_basics.html">Active Record Associations</a></dd>
|
49
|
+
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
|
50
|
+
<dt>Views</dt>
|
51
|
+
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
|
52
|
+
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
|
53
|
+
<dt>Controllers</dt>
|
54
|
+
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
|
55
|
+
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
|
56
|
+
</dl>
|
57
|
+
<dl class="R">
|
58
|
+
<dt>Digging Deeper</dt>
|
59
|
+
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
|
60
|
+
<dd><a href="i18n.html">Rails Internationalization API</a></dd>
|
61
|
+
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
|
62
|
+
<dd><a href="testing.html">Testing Rails Applications</a></dd>
|
63
|
+
<dd><a href="security.html">Securing Rails Applications</a></dd>
|
64
|
+
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
|
65
|
+
<dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
|
66
|
+
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
|
67
|
+
<dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
|
68
|
+
<dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
|
69
|
+
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
|
70
|
+
|
71
|
+
<dt>Extending Rails</dt>
|
72
|
+
<dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
|
73
|
+
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
|
74
|
+
<dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
|
75
|
+
|
76
|
+
<dt>Contributing to Ruby on Rails</dt>
|
77
|
+
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
|
78
|
+
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
|
79
|
+
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
|
80
|
+
|
81
|
+
<dt>Release Notes</dt>
|
82
|
+
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
|
83
|
+
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
|
84
|
+
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
|
85
|
+
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
|
86
|
+
</dl>
|
87
|
+
</div>
|
88
|
+
</li>
|
89
|
+
<li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
|
90
|
+
<li><a href="credits.html">Credits</a></li>
|
91
|
+
</ul>
|
92
|
+
</div>
|
93
|
+
</div>
|
94
|
+
<hr class="hide" />
|
95
|
+
|
96
|
+
<div id="feature">
|
97
|
+
<div class="wrapper">
|
98
|
+
<h2>Active Record Validations and Callbacks</h2>
|
99
|
+
<p>This guide teaches you how to hook into the life cycle of your Active Record objects. You will learn how to validate the state of objects before they go into the database, and how to perform custom operations at certain points in the object life cycle.</p>
|
100
|
+
<p>After reading this guide and trying out the presented concepts, we hope that you’ll be able to:</p>
|
101
|
+
<ul>
|
102
|
+
<li>Understand the life cycle of Active Record objects</li>
|
103
|
+
<li>Use the built-in Active Record validation helpers</li>
|
104
|
+
<li>Create your own custom validation methods</li>
|
105
|
+
<li>Work with the error messages generated by the validation process</li>
|
106
|
+
<li>Create callback methods that respond to events in the object life cycle</li>
|
107
|
+
<li>Create special classes that encapsulate common behavior for your callbacks</li>
|
108
|
+
<li>Create Observers that respond to life cycle events outside of the original class</li>
|
109
|
+
</ul>
|
110
|
+
|
111
|
+
<div id="subCol">
|
112
|
+
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
|
113
|
+
<ol class="chapters">
|
114
|
+
<li><a href="#the-object-life-cycle">The Object Life Cycle</a></li><li><a href="#validations-overview">Validations Overview</a><ul><li><a href="#why-use-validations">Why Use Validations?</a></li> <li><a href="#when-does-validation-happen">When Does Validation Happen?</a></li> <li><a href="#skipping-validations">Skipping Validations</a></li> <li><a href="#valid-and-invalid"><tt>valid?</tt> and <tt>invalid?</tt></a></li> <li><a href="#validations_overview-errors"><tt>errors[]</tt></a></li></ul></li><li><a href="#validation-helpers">Validation Helpers</a><ul><li><a href="#acceptance"><tt>acceptance</tt></a></li> <li><a href="#validates_associated"><tt>validates_associated</tt></a></li> <li><a href="#confirmation"><tt>confirmation</tt></a></li> <li><a href="#exclusion"><tt>exclusion</tt></a></li> <li><a href="#format"><tt>format</tt></a></li> <li><a href="#inclusion"><tt>inclusion</tt></a></li> <li><a href="#length"><tt>length</tt></a></li> <li><a href="#numericality"><tt>numericality</tt></a></li> <li><a href="#presence"><tt>presence</tt></a></li> <li><a href="#uniqueness"><tt>uniqueness</tt></a></li> <li><a href="#validates_with"><tt>validates_with</tt></a></li> <li><a href="#validates_each"><tt>validates_each</tt></a></li></ul></li><li><a href="#common-validation-options">Common Validation Options</a><ul><li><a href="#allow_nil"><tt>:allow_nil</tt></a></li> <li><a href="#allow_blank"><tt>:allow_blank</tt></a></li> <li><a href="#message"><tt>:message</tt></a></li> <li><a href="#on"><tt>:on</tt></a></li></ul></li><li><a href="#conditional-validation">Conditional Validation</a><ul><li><a href="#using-a-symbol-with-if-and-unless">Using a Symbol with <tt>:if</tt> and <tt>:unless</tt></a></li> <li><a href="#using-a-string-with-if-and-unless">Using a String with <tt>:if</tt> and <tt>:unless</tt></a></li> <li><a href="#using-a-proc-with-if-and-unless">Using a Proc with <tt>:if</tt> and <tt>:unless</tt></a></li> <li><a href="#grouping-conditional-validations">Grouping conditional validations</a></li></ul></li><li><a href="#performing-custom-validations">Performing Custom Validations</a><ul><li><a href="#custom-validators">Custom Validators</a></li> <li><a href="#custom-methods">Custom Methods</a></li></ul></li><li><a href="#working-with-validation-errors">Working with Validation Errors</a><ul><li><a href="#working_with_validation_errors-errors"><tt>errors</tt></a></li> <li><a href="#working_with_validation_errors-errors-2"><tt>errors[]</tt></a></li> <li><a href="#errors-add"><tt>errors.add</tt></a></li> <li><a href="#errors-base"><tt>errors[:base]</tt></a></li> <li><a href="#errors-clear"><tt>errors.clear</tt></a></li> <li><a href="#errors-size"><tt>errors.size</tt></a></li></ul></li><li><a href="#displaying-validation-errors-in-the-view">Displaying Validation Errors in the View</a><ul><li><a href="#installing-as-a-plugin">Installing as a plugin</a></li> <li><a href="#installing-as-a-gem">Installing as a Gem</a></li> <li><a href="#error_messages-and-error_messages_for"><tt>error_messages</tt> and <tt>error_messages_for</tt></a></li> <li><a href="#customizing-error-messages-css">Customizing the Error Messages <span class="caps">CSS</span></a></li> <li><a href="#customizing-the-error-messages-html">Customizing the Error Messages <span class="caps">HTML</span></a></li></ul></li><li><a href="#callbacks-overview">Callbacks Overview</a><ul><li><a href="#callback-registration">Callback Registration</a></li></ul></li><li><a href="#available-callbacks">Available Callbacks</a><ul><li><a href="#creating-an-object">Creating an Object</a></li> <li><a href="#updating-an-object">Updating an Object</a></li> <li><a href="#destroying-an-object">Destroying an Object</a></li> <li><a href="#after_initialize-and-after_find"><tt>after_initialize</tt> and <tt>after_find</tt></a></li></ul></li><li><a href="#running-callbacks">Running Callbacks</a></li><li><a href="#skipping-callbacks">Skipping Callbacks</a></li><li><a href="#halting-execution">Halting Execution</a></li><li><a href="#relational-callbacks">Relational Callbacks</a></li><li><a href="#conditional-callbacks">Conditional Callbacks</a><ul><li><a href="#using-if-and-unless-with-a-symbol">Using <tt>:if</tt> and <tt>:unless</tt> with a <tt>Symbol</tt></a></li> <li><a href="#using-if-and-unless-with-a-string">Using <tt>:if</tt> and <tt>:unless</tt> with a String</a></li> <li><a href="#using-if-and-unless-with-a-proc">Using <tt>:if</tt> and <tt>:unless</tt> with a <tt>Proc</tt></a></li> <li><a href="#multiple-conditions-for-callbacks">Multiple Conditions for Callbacks</a></li></ul></li><li><a href="#callback-classes">Callback Classes</a></li><li><a href="#observers">Observers</a><ul><li><a href="#creating-observers">Creating Observers</a></li> <li><a href="#registering-observers">Registering Observers</a></li> <li><a href="#sharing-observers">Sharing Observers</a></li></ul></li><li><a href="#transaction-callbacks">Transaction Callbacks</a></li></ol></div>
|
115
|
+
</div>
|
116
|
+
</div>
|
117
|
+
|
118
|
+
<div id="container">
|
119
|
+
<div class="wrapper">
|
120
|
+
<div id="mainCol">
|
121
|
+
<h3 id="the-object-life-cycle">1 The Object Life Cycle</h3>
|
122
|
+
<p>During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object life cycle</em> so that you can control your application and its data.</p>
|
123
|
+
<p>Validations allow you to ensure that only valid data is stored in your database. Callbacks and observers allow you to trigger logic before or after an alteration of an object’s state.</p>
|
124
|
+
<h3 id="validations-overview">2 Validations Overview</h3>
|
125
|
+
<p>Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture.</p>
|
126
|
+
<h4 id="why-use-validations">2.1 Why Use Validations?</h4>
|
127
|
+
<p>Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address.</p>
|
128
|
+
<p>There are several ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations, and model-level validations:</p>
|
129
|
+
<ul>
|
130
|
+
<li>Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.</li>
|
131
|
+
<li>Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user’s browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site.</li>
|
132
|
+
<li>Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it’s a good idea to <a href="http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model">keep your controllers skinny</a>, as it will make your application a pleasure to work with in the long run.</li>
|
133
|
+
<li>Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well.</li>
|
134
|
+
</ul>
|
135
|
+
<h4 id="when-does-validation-happen">2.2 When Does Validation Happen?</h4>
|
136
|
+
<p>There are two kinds of Active Record objects: those that correspond to a row inside your database and those that do not. When you create a fresh object, for example using the <tt>new</tt> method, that object does not belong to the database yet. Once you call <tt>save</tt> upon that object it will be saved into the appropriate database table. Active Record uses the <tt>new_record?</tt> instance method to determine whether an object is already in the database or not. Consider the following simple Active Record class:</p>
|
137
|
+
<div class="code_container">
|
138
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
139
|
+
class Person < ActiveRecord::Base
|
140
|
+
end
|
141
|
+
</pre>
|
142
|
+
</div>
|
143
|
+
<p>We can see how it works by looking at some <tt>rails console</tt> output:</p>
|
144
|
+
<div class="code_container">
|
145
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
146
|
+
>> p = Person.new(:name => "John Doe")
|
147
|
+
=> #<Person id: nil, name: "John Doe", created_at: nil, :updated_at: nil>
|
148
|
+
>> p.new_record?
|
149
|
+
=> true
|
150
|
+
>> p.save
|
151
|
+
=> true
|
152
|
+
>> p.new_record?
|
153
|
+
=> false
|
154
|
+
</pre>
|
155
|
+
</div>
|
156
|
+
<p>Creating and saving a new record will send an <span class="caps">SQL</span> <tt>INSERT</tt> operation to the database. Updating an existing record will send an <span class="caps">SQL</span> <tt>UPDATE</tt> operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the <tt>INSERT</tt> or <tt>UPDATE</tt> operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.</p>
|
157
|
+
<div class="warning"><p>There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it’s possible to save an object in the database in an invalid state if you aren’t careful.</p></div>
|
158
|
+
<p>The following methods trigger validations, and will save the object to the database only if the object is valid:</p>
|
159
|
+
<ul>
|
160
|
+
<li><tt>create</tt></li>
|
161
|
+
<li><tt>create!</tt></li>
|
162
|
+
<li><tt>save</tt></li>
|
163
|
+
<li><tt>save!</tt></li>
|
164
|
+
<li><tt>update</tt></li>
|
165
|
+
<li><tt>update_attributes</tt></li>
|
166
|
+
<li><tt>update_attributes!</tt></li>
|
167
|
+
</ul>
|
168
|
+
<p>The bang versions (e.g. <tt>save!</tt>) raise an exception if the record is invalid. The non-bang versions don’t: <tt>save</tt> and <tt>update_attributes</tt> return <tt>false</tt>, <tt>create</tt> and <tt>update</tt> just return the objects.</p>
|
169
|
+
<h4 id="skipping-validations">2.3 Skipping Validations</h4>
|
170
|
+
<p>The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.</p>
|
171
|
+
<ul>
|
172
|
+
<li><tt>decrement!</tt></li>
|
173
|
+
<li><tt>decrement_counter</tt></li>
|
174
|
+
<li><tt>increment!</tt></li>
|
175
|
+
<li><tt>increment_counter</tt></li>
|
176
|
+
<li><tt>toggle!</tt></li>
|
177
|
+
<li><tt>touch</tt></li>
|
178
|
+
<li><tt>update_all</tt></li>
|
179
|
+
<li><tt>update_attribute</tt></li>
|
180
|
+
<li><tt>update_column</tt></li>
|
181
|
+
<li><tt>update_counters</tt></li>
|
182
|
+
</ul>
|
183
|
+
<p>Note that <tt>save</tt> also has the ability to skip validations if passed <tt>:validate => false</tt> as argument. This technique should be used with caution.</p>
|
184
|
+
<ul>
|
185
|
+
<li><tt>save(:validate => false)</tt></li>
|
186
|
+
</ul>
|
187
|
+
<h4 id="valid-and-invalid">2.4 <tt>valid?</tt> and <tt>invalid?</tt></h4>
|
188
|
+
<p>To verify whether or not an object is valid, Rails uses the <tt>valid?</tt> method. You can also use this method on your own. <tt>valid?</tt> triggers your validations and returns true if no errors were found in the object, and false otherwise.</p>
|
189
|
+
<div class="code_container">
|
190
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
191
|
+
class Person < ActiveRecord::Base
|
192
|
+
validates :name, :presence => true
|
193
|
+
end
|
194
|
+
|
195
|
+
Person.create(:name => "John Doe").valid? # => true
|
196
|
+
Person.create(:name => nil).valid? # => false
|
197
|
+
</pre>
|
198
|
+
</div>
|
199
|
+
<p>After Active Record has performed validations, any errors found can be accessed through the <tt>errors</tt> instance method, which returns a collection of errors. By definition, an object is valid if this collection is empty after running validations.</p>
|
200
|
+
<p>Note that an object instantiated with <tt>new</tt> will not report errors even if it’s technically invalid, because validations are not run when using <tt>new</tt>.</p>
|
201
|
+
<div class="code_container">
|
202
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
203
|
+
class Person < ActiveRecord::Base
|
204
|
+
validates :name, :presence => true
|
205
|
+
end
|
206
|
+
|
207
|
+
>> p = Person.new
|
208
|
+
=> #<Person id: nil, name: nil>
|
209
|
+
>> p.errors
|
210
|
+
=> {}
|
211
|
+
|
212
|
+
>> p.valid?
|
213
|
+
=> false
|
214
|
+
>> p.errors
|
215
|
+
=> {:name=>["can't be blank"]}
|
216
|
+
|
217
|
+
>> p = Person.create
|
218
|
+
=> #<Person id: nil, name: nil>
|
219
|
+
>> p.errors
|
220
|
+
=> {:name=>["can't be blank"]}
|
221
|
+
|
222
|
+
>> p.save
|
223
|
+
=> false
|
224
|
+
|
225
|
+
>> p.save!
|
226
|
+
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
|
227
|
+
|
228
|
+
>> Person.create!
|
229
|
+
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
|
230
|
+
</pre>
|
231
|
+
</div>
|
232
|
+
<p><tt>invalid?</tt> is simply the inverse of <tt>valid?</tt>. <tt>invalid?</tt> triggers your validations, returning true if any errors were found in the object, and false otherwise.</p>
|
233
|
+
<h4 id="validations_overview-errors">2.5 <tt>errors[]</tt></h4>
|
234
|
+
<p>To verify whether or not a particular attribute of an object is valid, you can use <tt>errors[:attribute]</tt>. It returns an array of all the errors for <tt>:attribute</tt>. If there are no errors on the specified attribute, an empty array is returned.</p>
|
235
|
+
<p>This method is only useful <em>after</em> validations have been run, because it only inspects the errors collection and does not trigger validations itself. It’s different from the <tt>ActiveRecord::Base#invalid?</tt> method explained above because it doesn’t verify the validity of the object as a whole. It only checks to see whether there are errors found on an individual attribute of the object.</p>
|
236
|
+
<div class="code_container">
|
237
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
238
|
+
class Person < ActiveRecord::Base
|
239
|
+
validates :name, :presence => true
|
240
|
+
end
|
241
|
+
|
242
|
+
>> Person.new.errors[:name].any? # => false
|
243
|
+
>> Person.create.errors[:name].any? # => true
|
244
|
+
</pre>
|
245
|
+
</div>
|
246
|
+
<p>We’ll cover validation errors in greater depth in the <a href="#working-with-validation-errors">Working with Validation Errors</a> section. For now, let’s turn to the built-in validation helpers that Rails provides by default.</p>
|
247
|
+
<h3 id="validation-helpers">3 Validation Helpers</h3>
|
248
|
+
<p>Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object’s <tt>errors</tt> collection, and this message is associated with the attribute being validated.</p>
|
249
|
+
<p>Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.</p>
|
250
|
+
<p>All of them accept the <tt>:on</tt> and <tt>:message</tt> options, which define when the validation should be run and what message should be added to the <tt>errors</tt> collection if it fails, respectively. The <tt>:on</tt> option takes one of the values <tt>:save</tt> (the default), <tt>:create</tt> or <tt>:update</tt>. There is a default error message for each one of the validation helpers. These messages are used when the <tt>:message</tt> option isn’t specified. Let’s take a look at each one of the available helpers.</p>
|
251
|
+
<h4 id="acceptance">3.1 <tt>acceptance</tt></h4>
|
252
|
+
<p>Validates that a checkbox on the user interface was checked when a form was submitted. This is typically used when the user needs to agree to your application’s terms of service, confirm reading some text, or any similar concept. This validation is very specific to web applications and this ‘acceptance’ does not need to be recorded anywhere in your database (if you don’t have a field for it, the helper will just create a virtual attribute).</p>
|
253
|
+
<div class="code_container">
|
254
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
255
|
+
class Person < ActiveRecord::Base
|
256
|
+
validates :terms_of_service, :acceptance => true
|
257
|
+
end
|
258
|
+
</pre>
|
259
|
+
</div>
|
260
|
+
<p>The default error message for this helper is “<em>must be accepted</em>”.</p>
|
261
|
+
<p>It can receive an <tt>:accept</tt> option, which determines the value that will be considered acceptance. It defaults to “1” and can be easily changed.</p>
|
262
|
+
<div class="code_container">
|
263
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
264
|
+
class Person < ActiveRecord::Base
|
265
|
+
validates :terms_of_service, :acceptance => { :accept => 'yes' }
|
266
|
+
end
|
267
|
+
</pre>
|
268
|
+
</div>
|
269
|
+
<h4 id="validates_associated">3.2 <tt>validates_associated</tt></h4>
|
270
|
+
<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>
|
271
|
+
<div class="code_container">
|
272
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
273
|
+
class Library < ActiveRecord::Base
|
274
|
+
has_many :books
|
275
|
+
validates_associated :books
|
276
|
+
end
|
277
|
+
</pre>
|
278
|
+
</div>
|
279
|
+
<p>This validation will work with all of the association types.</p>
|
280
|
+
<div class="warning"><p>Don’t use <tt>validates_associated</tt> on both ends of your associations. They would call each other in an infinite loop.</p></div>
|
281
|
+
<p>The default error message for <tt>validates_associated</tt> is “<em>is invalid</em>”. Note that each associated object will contain its own <tt>errors</tt> collection; errors do not bubble up to the calling model.</p>
|
282
|
+
<h4 id="confirmation">3.3 <tt>confirmation</tt></h4>
|
283
|
+
<p>You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with “_confirmation” appended.</p>
|
284
|
+
<div class="code_container">
|
285
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
286
|
+
class Person < ActiveRecord::Base
|
287
|
+
validates :email, :confirmation => true
|
288
|
+
end
|
289
|
+
</pre>
|
290
|
+
</div>
|
291
|
+
<p>In your view template you could use something like</p>
|
292
|
+
<div class="code_container">
|
293
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
294
|
+
<%= text_field :person, :email %>
|
295
|
+
<%= text_field :person, :email_confirmation %>
|
296
|
+
</pre>
|
297
|
+
</div>
|
298
|
+
<p>This check is performed only if <tt>email_confirmation</tt> is not <tt>nil</tt>. To require confirmation, make sure to add a presence check for the confirmation attribute (we’ll take a look at <tt>presence</tt> later on this guide):</p>
|
299
|
+
<div class="code_container">
|
300
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
301
|
+
class Person < ActiveRecord::Base
|
302
|
+
validates :email, :confirmation => true
|
303
|
+
validates :email_confirmation, :presence => true
|
304
|
+
end
|
305
|
+
</pre>
|
306
|
+
</div>
|
307
|
+
<p>The default error message for this helper is “<em>doesn’t match confirmation</em>”.</p>
|
308
|
+
<h4 id="exclusion">3.4 <tt>exclusion</tt></h4>
|
309
|
+
<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>
|
310
|
+
<div class="code_container">
|
311
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
312
|
+
class Account < ActiveRecord::Base
|
313
|
+
validates :subdomain, :exclusion => { :in => %w(www us ca jp),
|
314
|
+
:message => "Subdomain %{value} is reserved." }
|
315
|
+
end
|
316
|
+
</pre>
|
317
|
+
</div>
|
318
|
+
<p>The <tt>exclusion</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. This example uses the <tt>:message</tt> option to show how you can include the attribute’s value.</p>
|
319
|
+
<p>The default error message is “<em>is reserved</em>”.</p>
|
320
|
+
<h4 id="format">3.5 <tt>format</tt></h4>
|
321
|
+
<p>This helper validates the attributes’ values by testing whether they match a given regular expression, which is specified using the <tt>:with</tt> option.</p>
|
322
|
+
<div class="code_container">
|
323
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
324
|
+
class Product < ActiveRecord::Base
|
325
|
+
validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/,
|
326
|
+
:message => "Only letters allowed" }
|
327
|
+
end
|
328
|
+
</pre>
|
329
|
+
</div>
|
330
|
+
<p>The default error message is “<em>is invalid</em>”.</p>
|
331
|
+
<h4 id="inclusion">3.6 <tt>inclusion</tt></h4>
|
332
|
+
<p>This helper validates that the attributes’ values are included in a given set. In fact, this set can be any enumerable object.</p>
|
333
|
+
<div class="code_container">
|
334
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
335
|
+
class Coffee < ActiveRecord::Base
|
336
|
+
validates :size, :inclusion => { :in => %w(small medium large),
|
337
|
+
:message => "%{value} is not a valid size" }
|
338
|
+
end
|
339
|
+
</pre>
|
340
|
+
</div>
|
341
|
+
<p>The <tt>inclusion</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. The previous example uses the <tt>:message</tt> option to show how you can include the attribute’s value.</p>
|
342
|
+
<p>The default error message for this helper is “<em>is not included in the list</em>”.</p>
|
343
|
+
<h4 id="length">3.7 <tt>length</tt></h4>
|
344
|
+
<p>This helper validates the length of the attributes’ values. It provides a variety of options, so you can specify length constraints in different ways:</p>
|
345
|
+
<div class="code_container">
|
346
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
347
|
+
class Person < ActiveRecord::Base
|
348
|
+
validates :name, :length => { :minimum => 2 }
|
349
|
+
validates :bio, :length => { :maximum => 500 }
|
350
|
+
validates :password, :length => { :in => 6..20 }
|
351
|
+
validates :registration_number, :length => { :is => 6 }
|
352
|
+
end
|
353
|
+
</pre>
|
354
|
+
</div>
|
355
|
+
<p>The possible length constraint options are:</p>
|
356
|
+
<ul>
|
357
|
+
<li><tt>:minimum</tt> – The attribute cannot have less than the specified length.</li>
|
358
|
+
<li><tt>:maximum</tt> – The attribute cannot have more than the specified length.</li>
|
359
|
+
<li><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 range.</li>
|
360
|
+
<li><tt>:is</tt> – The attribute length must be equal to the given value.</li>
|
361
|
+
</ul>
|
362
|
+
<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 <tt>%{count}</tt> as a placeholder for the number corresponding to the length constraint being used. You can still use the <tt>:message</tt> option to specify an error message.</p>
|
363
|
+
<div class="code_container">
|
364
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
365
|
+
class Person < ActiveRecord::Base
|
366
|
+
validates :bio, :length => { :maximum => 1000,
|
367
|
+
:too_long => "%{count} characters is the maximum allowed" }
|
368
|
+
end
|
369
|
+
</pre>
|
370
|
+
</div>
|
371
|
+
<p>This helper counts characters by default, but you can split the value in a different way using the <tt>:tokenizer</tt> option:</p>
|
372
|
+
<div class="code_container">
|
373
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
374
|
+
class Essay < ActiveRecord::Base
|
375
|
+
validates :content, :length => {
|
376
|
+
:minimum => 300,
|
377
|
+
:maximum => 400,
|
378
|
+
:tokenizer => lambda { |str| str.scan(/\w+/) },
|
379
|
+
:too_short => "must have at least %{count} words",
|
380
|
+
:too_long => "must have at most %{count} words"
|
381
|
+
}
|
382
|
+
end
|
383
|
+
</pre>
|
384
|
+
</div>
|
385
|
+
<p>Note that the default error messages are plural (e.g., “is too short (minimum is %{count} characters)”). For this reason, when <tt>:minimum</tt> is 1 you should provide a personalized message or use <tt>validates_presence_of</tt> instead. When <tt>:in</tt> or <tt>:within</tt> have a lower limit of 1, you should either provide a personalized message or call <tt>presence</tt> prior to <tt>length</tt>.</p>
|
386
|
+
<p>The <tt>size</tt> helper is an alias for <tt>length</tt>.</p>
|
387
|
+
<h4 id="numericality">3.8 <tt>numericality</tt></h4>
|
388
|
+
<p>This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by an integral or floating point number. To specify that only integral numbers are allowed set <tt>:only_integer</tt> to true.</p>
|
389
|
+
<p>If you set <tt>:only_integer</tt> to <tt>true</tt>, then it will use the</p>
|
390
|
+
<div class="code_container">
|
391
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
392
|
+
/\A[+-]?\d+\Z/
|
393
|
+
</pre>
|
394
|
+
</div>
|
395
|
+
<p>regular expression to validate the attribute’s value. Otherwise, it will try to convert the value to a number using <tt>Float</tt>.</p>
|
396
|
+
<div class="warning"><p>Note that the regular expression above allows a trailing newline character.</p></div>
|
397
|
+
<div class="code_container">
|
398
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
399
|
+
class Player < ActiveRecord::Base
|
400
|
+
validates :points, :numericality => true
|
401
|
+
validates :games_played, :numericality => { :only_integer => true }
|
402
|
+
end
|
403
|
+
</pre>
|
404
|
+
</div>
|
405
|
+
<p>Besides <tt>:only_integer</tt>, this helper also accepts the following options to add constraints to acceptable values:</p>
|
406
|
+
<ul>
|
407
|
+
<li><tt>:greater_than</tt> – Specifies the value must be greater than the supplied value. The default error message for this option is “<em>must be greater than %{count}</em>”.</li>
|
408
|
+
<li><tt>:greater_than_or_equal_to</tt> – Specifies the value must be greater than or equal to the supplied value. The default error message for this option is “<em>must be greater than or equal to %{count}</em>”.</li>
|
409
|
+
<li><tt>:equal_to</tt> – Specifies the value must be equal to the supplied value. The default error message for this option is “<em>must be equal to %{count}</em>”.</li>
|
410
|
+
<li><tt>:less_than</tt> – Specifies the value must be less than the supplied value. The default error message for this option is “<em>must be less than %{count}</em>”.</li>
|
411
|
+
<li><tt>:less_than_or_equal_to</tt> – Specifies the value must be less than or equal the supplied value. The default error message for this option is “<em>must be less than or equal to %{count}</em>”.</li>
|
412
|
+
<li><tt>:odd</tt> – Specifies the value must be an odd number if set to true. The default error message for this option is “<em>must be odd</em>”.</li>
|
413
|
+
<li><tt>:even</tt> – Specifies the value must be an even number if set to true. The default error message for this option is “<em>must be even</em>”.</li>
|
414
|
+
</ul>
|
415
|
+
<p>The default error message is “<em>is not a number</em>”.</p>
|
416
|
+
<h4 id="presence">3.9 <tt>presence</tt></h4>
|
417
|
+
<p>This helper validates that the specified attributes are not empty. It uses the <tt>blank?</tt> method to check if the value is either <tt>nil</tt> or a blank string, that is, a string that is either empty or consists of whitespace.</p>
|
418
|
+
<div class="code_container">
|
419
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
420
|
+
class Person < ActiveRecord::Base
|
421
|
+
validates :name, :login, :email, :presence => true
|
422
|
+
end
|
423
|
+
</pre>
|
424
|
+
</div>
|
425
|
+
<p>If you want to be sure that an association is present, you’ll need to test whether the foreign key used to map the association is present, and not the associated object itself.</p>
|
426
|
+
<div class="code_container">
|
427
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
428
|
+
class LineItem < ActiveRecord::Base
|
429
|
+
belongs_to :order
|
430
|
+
validates :order_id, :presence => true
|
431
|
+
end
|
432
|
+
</pre>
|
433
|
+
</div>
|
434
|
+
<p>Since <tt>false.blank?</tt> is true, if you want to validate the presence of a boolean field you should use <tt>validates :field_name, :inclusion => { :in => [true, false] }</tt>.</p>
|
435
|
+
<p>The default error message is “<em>can’t be empty</em>”.</p>
|
436
|
+
<h4 id="uniqueness">3.10 <tt>uniqueness</tt></h4>
|
437
|
+
<p>This helper validates that the attribute’s value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index in your database.</p>
|
438
|
+
<div class="code_container">
|
439
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
440
|
+
class Account < ActiveRecord::Base
|
441
|
+
validates :email, :uniqueness => true
|
442
|
+
end
|
443
|
+
</pre>
|
444
|
+
</div>
|
445
|
+
<p>The validation happens by performing an <span class="caps">SQL</span> query into the model’s table, searching for an existing record with the same value in that attribute.</p>
|
446
|
+
<p>There is a <tt>:scope</tt> option that you can use to specify other attributes that are used to limit the uniqueness check:</p>
|
447
|
+
<div class="code_container">
|
448
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
449
|
+
class Holiday < ActiveRecord::Base
|
450
|
+
validates :name, :uniqueness => { :scope => :year,
|
451
|
+
:message => "should happen once per year" }
|
452
|
+
end
|
453
|
+
</pre>
|
454
|
+
</div>
|
455
|
+
<p>There is also a <tt>:case_sensitive</tt> option that you can use to define whether the uniqueness constraint will be case sensitive or not. This option defaults to true.</p>
|
456
|
+
<div class="code_container">
|
457
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
458
|
+
class Person < ActiveRecord::Base
|
459
|
+
validates :name, :uniqueness => { :case_sensitive => false }
|
460
|
+
end
|
461
|
+
</pre>
|
462
|
+
</div>
|
463
|
+
<div class="warning"><p>Note that some databases are configured to perform case-insensitive searches anyway.</p></div>
|
464
|
+
<p>The default error message is “<em>has already been taken</em>”.</p>
|
465
|
+
<h4 id="validates_with">3.11 <tt>validates_with</tt></h4>
|
466
|
+
<p>This helper passes the record to a separate class for validation.</p>
|
467
|
+
<div class="code_container">
|
468
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
469
|
+
class Person < ActiveRecord::Base
|
470
|
+
validates_with GoodnessValidator
|
471
|
+
end
|
472
|
+
|
473
|
+
class GoodnessValidator < ActiveModel::Validator
|
474
|
+
def validate(record)
|
475
|
+
if record.first_name == "Evil"
|
476
|
+
record.errors[:base] << "This person is evil"
|
477
|
+
end
|
478
|
+
end
|
479
|
+
end
|
480
|
+
</pre>
|
481
|
+
</div>
|
482
|
+
<div class="note"><p>Errors added to <tt>record.errors[:base]</tt> relate to the state of the record as a whole, and not to a specific attribute.</p></div>
|
483
|
+
<p>The <tt>validates_with</tt> helper takes a class, or a list of classes to use for validation. There is no default error message for <tt>validates_with</tt>. You must manually add errors to the record’s errors collection in the validator class.</p>
|
484
|
+
<p>To implement the validate method, you must have a <tt>record</tt> parameter defined, which is the record to be validated.</p>
|
485
|
+
<p>Like all other validations, <tt>validates_with</tt> takes the <tt>:if</tt>, <tt>:unless</tt> and <tt>:on</tt> options. If you pass any other options, it will send those options to the validator class as <tt>options</tt>:</p>
|
486
|
+
<div class="code_container">
|
487
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
488
|
+
class Person < ActiveRecord::Base
|
489
|
+
validates_with GoodnessValidator, :fields => [:first_name, :last_name]
|
490
|
+
end
|
491
|
+
|
492
|
+
class GoodnessValidator < ActiveModel::Validator
|
493
|
+
def validate(record)
|
494
|
+
if options[:fields].any?{|field| record.send(field) == "Evil" }
|
495
|
+
record.errors[:base] << "This person is evil"
|
496
|
+
end
|
497
|
+
end
|
498
|
+
end
|
499
|
+
</pre>
|
500
|
+
</div>
|
501
|
+
<h4 id="validates_each">3.12 <tt>validates_each</tt></h4>
|
502
|
+
<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>
|
503
|
+
<div class="code_container">
|
504
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
505
|
+
class Person < ActiveRecord::Base
|
506
|
+
validates_each :name, :surname do |record, attr, value|
|
507
|
+
record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
|
508
|
+
end
|
509
|
+
end
|
510
|
+
</pre>
|
511
|
+
</div>
|
512
|
+
<p>The block receives the record, the attribute’s name and the attribute’s value. You can do anything you like to check for valid data within the block. If your validation fails, you should add an error message to the model, therefore making it invalid.</p>
|
513
|
+
<h3 id="common-validation-options">4 Common Validation Options</h3>
|
514
|
+
<p>These are common validation options:</p>
|
515
|
+
<h4 id="allow_nil">4.1 <tt>:allow_nil</tt></h4>
|
516
|
+
<p>The <tt>:allow_nil</tt> option skips the validation when the value being validated is <tt>nil</tt>.</p>
|
517
|
+
<div class="code_container">
|
518
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
519
|
+
class Coffee < ActiveRecord::Base
|
520
|
+
validates :size, :inclusion => { :in => %w(small medium large),
|
521
|
+
:message => "%{value} is not a valid size" }, :allow_nil => true
|
522
|
+
end
|
523
|
+
</pre>
|
524
|
+
</div>
|
525
|
+
<div class="info"><p><tt>:allow_nil</tt> is ignored by the presence validator.</p></div>
|
526
|
+
<h4 id="allow_blank">4.2 <tt>:allow_blank</tt></h4>
|
527
|
+
<p>The <tt>:allow_blank</tt> option is similar to the <tt>:allow_nil</tt> option. This option will let validation pass if the attribute’s value is <tt>blank?</tt>, like <tt>nil</tt> or an empty string for example.</p>
|
528
|
+
<div class="code_container">
|
529
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
530
|
+
class Topic < ActiveRecord::Base
|
531
|
+
validates :title, :length => { :is => 5 }, :allow_blank => true
|
532
|
+
end
|
533
|
+
|
534
|
+
Topic.create("title" => "").valid? # => true
|
535
|
+
Topic.create("title" => nil).valid? # => true
|
536
|
+
</pre>
|
537
|
+
</div>
|
538
|
+
<div class="info"><p><tt>:allow_blank</tt> is ignored by the presence validator.</p></div>
|
539
|
+
<h4 id="message">4.3 <tt>:message</tt></h4>
|
540
|
+
<p>As you’ve already seen, the <tt>:message</tt> option lets you specify the message that will be added to the <tt>errors</tt> collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.</p>
|
541
|
+
<h4 id="on">4.4 <tt>:on</tt></h4>
|
542
|
+
<p>The <tt>:on</tt> option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be run 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>
|
543
|
+
<div class="code_container">
|
544
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
545
|
+
class Person < ActiveRecord::Base
|
546
|
+
# it will be possible to update email with a duplicated value
|
547
|
+
validates :email, :uniqueness => true, :on => :create
|
548
|
+
|
549
|
+
# it will be possible to create the record with a non-numerical age
|
550
|
+
validates :age, :numericality => true, :on => :update
|
551
|
+
|
552
|
+
# the default (validates on both create and update)
|
553
|
+
validates :name, :presence => true, :on => :save
|
554
|
+
end
|
555
|
+
</pre>
|
556
|
+
</div>
|
557
|
+
<h3 id="conditional-validation">5 Conditional Validation</h3>
|
558
|
+
<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 <tt>Proc</tt>. 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>
|
559
|
+
<h4 id="using-a-symbol-with-if-and-unless">5.1 Using a Symbol with <tt>:if</tt> and <tt>:unless</tt></h4>
|
560
|
+
<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>
|
561
|
+
<div class="code_container">
|
562
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
563
|
+
class Order < ActiveRecord::Base
|
564
|
+
validates :card_number, :presence => true, :if => :paid_with_card?
|
565
|
+
|
566
|
+
def paid_with_card?
|
567
|
+
payment_type == "card"
|
568
|
+
end
|
569
|
+
end
|
570
|
+
</pre>
|
571
|
+
</div>
|
572
|
+
<h4 id="using-a-string-with-if-and-unless">5.2 Using a String with <tt>:if</tt> and <tt>:unless</tt></h4>
|
573
|
+
<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>
|
574
|
+
<div class="code_container">
|
575
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
576
|
+
class Person < ActiveRecord::Base
|
577
|
+
validates :surname, :presence => true, :if => "name.nil?"
|
578
|
+
end
|
579
|
+
</pre>
|
580
|
+
</div>
|
581
|
+
<h4 id="using-a-proc-with-if-and-unless">5.3 Using a Proc with <tt>:if</tt> and <tt>:unless</tt></h4>
|
582
|
+
<p>Finally, it’s possible to associate <tt>:if</tt> and <tt>:unless</tt> with a <tt>Proc</tt> object which will be called. Using a <tt>Proc</tt> object gives you the ability to write an inline condition instead of a separate method. This option is best suited for one-liners.</p>
|
583
|
+
<div class="code_container">
|
584
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
585
|
+
class Account < ActiveRecord::Base
|
586
|
+
validates :password, :confirmation => true,
|
587
|
+
:unless => Proc.new { |a| a.password.blank? }
|
588
|
+
end
|
589
|
+
</pre>
|
590
|
+
</div>
|
591
|
+
<h4 id="grouping-conditional-validations">5.4 Grouping conditional validations</h4>
|
592
|
+
<p>Sometimes it is useful to have multiple validations use one condition, it can be easily achieved using <tt>with_options</tt>.</p>
|
593
|
+
<div class="code_container">
|
594
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
595
|
+
class User < ActiveRecord::Base
|
596
|
+
with_options :if => :is_admin? do |admin|
|
597
|
+
admin.validates :password, :length => { :minimum => 10 }
|
598
|
+
admin.validates :email, :presence => true
|
599
|
+
end
|
600
|
+
end
|
601
|
+
</pre>
|
602
|
+
</div>
|
603
|
+
<p>All validations inside of <tt>with_options</tt> block will have automatically passed the condition <tt>:if => :is_admin?</tt></p>
|
604
|
+
<h3 id="performing-custom-validations">6 Performing Custom Validations</h3>
|
605
|
+
<p>When the built-in validation helpers are not enough for your needs, you can write your own validators or validation methods as you prefer.</p>
|
606
|
+
<h4 id="custom-validators">6.1 Custom Validators</h4>
|
607
|
+
<p>Custom validators are classes that extend <tt>ActiveModel::Validator</tt>. These classes must implement a <tt>validate</tt> method which takes a record as an argument and performs the validation on it. The custom validator is called using the <tt>validates_with</tt> method.</p>
|
608
|
+
<div class="code_container">
|
609
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
610
|
+
class MyValidator < ActiveModel::Validator
|
611
|
+
def validate(record)
|
612
|
+
unless record.name.starts_with? 'X'
|
613
|
+
record.errors[:name] << 'Need a name starting with X please!'
|
614
|
+
end
|
615
|
+
end
|
616
|
+
end
|
617
|
+
|
618
|
+
class Person
|
619
|
+
include ActiveModel::Validations
|
620
|
+
validates_with MyValidator
|
621
|
+
end
|
622
|
+
</pre>
|
623
|
+
</div>
|
624
|
+
<p>The easiest way to add custom validators for validating individual attributes is with the convenient <tt>ActiveModel::EachValidator</tt>. In this case, the custom validator class must implement a <tt>validate_each</tt> method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance.</p>
|
625
|
+
<div class="code_container">
|
626
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
627
|
+
class EmailValidator < ActiveModel::EachValidator
|
628
|
+
def validate_each(record, attribute, value)
|
629
|
+
unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
|
630
|
+
record.errors[attribute] << (options[:message] || "is not an email")
|
631
|
+
end
|
632
|
+
end
|
633
|
+
end
|
634
|
+
|
635
|
+
class Person < ActiveRecord::Base
|
636
|
+
validates :email, :presence => true, :email => true
|
637
|
+
end
|
638
|
+
</pre>
|
639
|
+
</div>
|
640
|
+
<p>As shown in the example, you can also combine standard validations with your own custom validators.</p>
|
641
|
+
<h4 id="custom-methods">6.2 Custom Methods</h4>
|
642
|
+
<p>You can also create methods that verify the state of your models and add messages to the <tt>errors</tt> collection when they are invalid. You must then register these 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.</p>
|
643
|
+
<p>You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.</p>
|
644
|
+
<div class="code_container">
|
645
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
646
|
+
class Invoice < ActiveRecord::Base
|
647
|
+
validate :expiration_date_cannot_be_in_the_past,
|
648
|
+
:discount_cannot_be_greater_than_total_value
|
649
|
+
|
650
|
+
def expiration_date_cannot_be_in_the_past
|
651
|
+
if !expiration_date.blank? and expiration_date < Date.today
|
652
|
+
errors.add(:expiration_date, "can't be in the past")
|
653
|
+
end
|
654
|
+
end
|
655
|
+
|
656
|
+
def discount_cannot_be_greater_than_total_value
|
657
|
+
if discount > total_value
|
658
|
+
errors.add(:discount, "can't be greater than total value")
|
659
|
+
end
|
660
|
+
end
|
661
|
+
end
|
662
|
+
</pre>
|
663
|
+
</div>
|
664
|
+
<p>You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices:</p>
|
665
|
+
<div class="code_container">
|
666
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
667
|
+
ActiveRecord::Base.class_eval do
|
668
|
+
def self.validates_as_choice(attr_name, n, options={})
|
669
|
+
validates attr_name, :inclusion => { {:in => 1..n}.merge(options) }
|
670
|
+
end
|
671
|
+
end
|
672
|
+
</pre>
|
673
|
+
</div>
|
674
|
+
<p>Simply reopen <tt>ActiveRecord::Base</tt> and define a class method like that. You’d typically put this code somewhere in <tt>config/initializers</tt>. You can use this helper like this:</p>
|
675
|
+
<div class="code_container">
|
676
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
677
|
+
class Movie < ActiveRecord::Base
|
678
|
+
validates_as_choice :rating, 5
|
679
|
+
end
|
680
|
+
</pre>
|
681
|
+
</div>
|
682
|
+
<h3 id="working-with-validation-errors">7 Working with Validation Errors</h3>
|
683
|
+
<p>In addition to the <tt>valid?</tt> and <tt>invalid?</tt> methods covered earlier, Rails provides a number of methods for working with the <tt>errors</tt> collection and inquiring about the validity of objects.</p>
|
684
|
+
<p>The following is a list of the most commonly used methods. Please refer to the <tt>ActiveRecord::Errors</tt> documentation for a list of all the available methods.</p>
|
685
|
+
<h4 id="working_with_validation_errors-errors">7.1 <tt>errors</tt></h4>
|
686
|
+
<p>Returns an instance of the class <tt>ActiveModel::Errors</tt> (which behaves like an ordered hash) containing all errors. Each key is the attribute name and the value is an array of strings with all errors.</p>
|
687
|
+
<div class="code_container">
|
688
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
689
|
+
class Person < ActiveRecord::Base
|
690
|
+
validates :name, :presence => true, :length => { :minimum => 3 }
|
691
|
+
end
|
692
|
+
|
693
|
+
person = Person.new
|
694
|
+
person.valid? # => false
|
695
|
+
person.errors
|
696
|
+
# => {:name => ["can't be blank", "is too short (minimum is 3 characters)"]}
|
697
|
+
|
698
|
+
person = Person.new(:name => "John Doe")
|
699
|
+
person.valid? # => true
|
700
|
+
person.errors # => []
|
701
|
+
</pre>
|
702
|
+
</div>
|
703
|
+
<h4 id="working_with_validation_errors-errors-2">7.2 <tt>errors[]</tt></h4>
|
704
|
+
<p><tt>errors[]</tt> is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.</p>
|
705
|
+
<div class="code_container">
|
706
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
707
|
+
class Person < ActiveRecord::Base
|
708
|
+
validates :name, :presence => true, :length => { :minimum => 3 }
|
709
|
+
end
|
710
|
+
|
711
|
+
person = Person.new(:name => "John Doe")
|
712
|
+
person.valid? # => true
|
713
|
+
person.errors[:name] # => []
|
714
|
+
|
715
|
+
person = Person.new(:name => "JD")
|
716
|
+
person.valid? # => false
|
717
|
+
person.errors[:name] # => ["is too short (minimum is 3 characters)"]
|
718
|
+
|
719
|
+
person = Person.new
|
720
|
+
person.valid? # => false
|
721
|
+
person.errors[:name]
|
722
|
+
# => ["can't be blank", "is too short (minimum is 3 characters)"]
|
723
|
+
</pre>
|
724
|
+
</div>
|
725
|
+
<h4 id="errors-add">7.3 <tt>errors.add</tt></h4>
|
726
|
+
<p>The <tt>add</tt> method lets you manually add messages that are related to particular attributes. You can use the <tt>errors.full_messages</tt> or <tt>errors.to_a</tt> methods to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). <tt>add</tt> receives the name of the attribute you want to add the message to, and the message itself.</p>
|
727
|
+
<div class="code_container">
|
728
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
729
|
+
class Person < ActiveRecord::Base
|
730
|
+
def a_method_used_for_validation_purposes
|
731
|
+
errors.add(:name, "cannot contain the characters !@#%*()_-+=")
|
732
|
+
end
|
733
|
+
end
|
734
|
+
|
735
|
+
person = Person.create(:name => "!@#")
|
736
|
+
|
737
|
+
person.errors[:name]
|
738
|
+
# => ["cannot contain the characters !@#%*()_-+="]
|
739
|
+
|
740
|
+
person.errors.full_messages
|
741
|
+
# => ["Name cannot contain the characters !@#%*()_-+="]
|
742
|
+
</pre>
|
743
|
+
</div>
|
744
|
+
<p>Another way to do this is using <tt>[]=</tt> setter</p>
|
745
|
+
<div class="code_container">
|
746
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
747
|
+
class Person < ActiveRecord::Base
|
748
|
+
def a_method_used_for_validation_purposes
|
749
|
+
errors[:name] = "cannot contain the characters !@#%*()_-+="
|
750
|
+
end
|
751
|
+
end
|
752
|
+
|
753
|
+
person = Person.create(:name => "!@#")
|
754
|
+
|
755
|
+
person.errors[:name]
|
756
|
+
# => ["cannot contain the characters !@#%*()_-+="]
|
757
|
+
|
758
|
+
person.errors.to_a
|
759
|
+
# => ["Name cannot contain the characters !@#%*()_-+="]
|
760
|
+
</pre>
|
761
|
+
</div>
|
762
|
+
<h4 id="errors-base">7.4 <tt>errors[:base]</tt></h4>
|
763
|
+
<p>You can add error 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 its attributes. Since <tt>errors[:base]</tt> is an array, you can simply add a string to it and it will be used as an error message.</p>
|
764
|
+
<div class="code_container">
|
765
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
766
|
+
class Person < ActiveRecord::Base
|
767
|
+
def a_method_used_for_validation_purposes
|
768
|
+
errors[:base] << "This person is invalid because ..."
|
769
|
+
end
|
770
|
+
end
|
771
|
+
</pre>
|
772
|
+
</div>
|
773
|
+
<h4 id="errors-clear">7.5 <tt>errors.clear</tt></h4>
|
774
|
+
<p>The <tt>clear</tt> method is used when you intentionally want to clear all the messages in the <tt>errors</tt> collection. Of course, calling <tt>errors.clear</tt> upon an invalid object won’t actually 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 again. If any of the validations fail, the <tt>errors</tt> collection will be filled again.</p>
|
775
|
+
<div class="code_container">
|
776
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
777
|
+
class Person < ActiveRecord::Base
|
778
|
+
validates :name, :presence => true, :length => { :minimum => 3 }
|
779
|
+
end
|
780
|
+
|
781
|
+
person = Person.new
|
782
|
+
person.valid? # => false
|
783
|
+
person.errors[:name]
|
784
|
+
# => ["can't be blank", "is too short (minimum is 3 characters)"]
|
785
|
+
|
786
|
+
person.errors.clear
|
787
|
+
person.errors.empty? # => true
|
788
|
+
|
789
|
+
p.save # => false
|
790
|
+
|
791
|
+
p.errors[:name]
|
792
|
+
# => ["can't be blank", "is too short (minimum is 3 characters)"]
|
793
|
+
</pre>
|
794
|
+
</div>
|
795
|
+
<h4 id="errors-size">7.6 <tt>errors.size</tt></h4>
|
796
|
+
<p>The <tt>size</tt> method returns the total number of error messages for the object.</p>
|
797
|
+
<div class="code_container">
|
798
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
799
|
+
class Person < ActiveRecord::Base
|
800
|
+
validates :name, :presence => true, :length => { :minimum => 3 }
|
801
|
+
end
|
802
|
+
|
803
|
+
person = Person.new
|
804
|
+
person.valid? # => false
|
805
|
+
person.errors.size # => 2
|
806
|
+
|
807
|
+
person = Person.new(:name => "Andrea", :email => "andrea@example.com")
|
808
|
+
person.valid? # => true
|
809
|
+
person.errors.size # => 0
|
810
|
+
</pre>
|
811
|
+
</div>
|
812
|
+
<h3 id="displaying-validation-errors-in-the-view">8 Displaying Validation Errors in the View</h3>
|
813
|
+
<p>Rails maintains an official plugin, DynamicForm, that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem.</p>
|
814
|
+
<h4 id="installing-as-a-plugin">8.1 Installing as a plugin</h4>
|
815
|
+
<div class="code_container">
|
816
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
817
|
+
$ rails plugin install git://github.com/joelmoss/dynamic_form.git
|
818
|
+
</pre>
|
819
|
+
</div>
|
820
|
+
<h4 id="installing-as-a-gem">8.2 Installing as a Gem</h4>
|
821
|
+
<p>Add this line in your Gemfile:</p>
|
822
|
+
<div class="code_container">
|
823
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
824
|
+
gem "dynamic_form"
|
825
|
+
</pre>
|
826
|
+
</div>
|
827
|
+
<p>Now you will have access to the two helper methods <tt>error_messages</tt> and <tt>error_messages_for</tt> in your view templates.</p>
|
828
|
+
<h4 id="error_messages-and-error_messages_for">8.3 <tt>error_messages</tt> and <tt>error_messages_for</tt></h4>
|
829
|
+
<p>When creating a form with the <tt>form_for</tt> helper, you can use the <tt>error_messages</tt> method on the form builder to render all failed validation messages for the current model instance.</p>
|
830
|
+
<div class="code_container">
|
831
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
832
|
+
class Product < ActiveRecord::Base
|
833
|
+
validates :description, :value, :presence => true
|
834
|
+
validates :value, :numericality => true, :allow_nil => true
|
835
|
+
end
|
836
|
+
</pre>
|
837
|
+
</div>
|
838
|
+
<div class="code_container">
|
839
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
840
|
+
<%= form_for(@product) do |f| %>
|
841
|
+
<%= f.error_messages %>
|
842
|
+
<p>
|
843
|
+
<%= f.label :description %><br />
|
844
|
+
<%= f.text_field :description %>
|
845
|
+
</p>
|
846
|
+
<p>
|
847
|
+
<%= f.label :value %><br />
|
848
|
+
<%= f.text_field :value %>
|
849
|
+
</p>
|
850
|
+
<p>
|
851
|
+
<%= f.submit "Create" %>
|
852
|
+
</p>
|
853
|
+
<% end %>
|
854
|
+
</pre>
|
855
|
+
</div>
|
856
|
+
<p>If you submit the form with empty fields, the result will be similar to the one shown below:</p>
|
857
|
+
<p><img src="images/error_messages.png" title="Error messages" alt="Error messages" /></p>
|
858
|
+
<div class="note"><p>The appearance of the generated <span class="caps">HTML</span> will be different from the one shown, unless you have used scaffolding. See <a href="#customizing-error-messages-css">Customizing the Error Messages <span class="caps">CSS</span></a>.</p></div>
|
859
|
+
<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 is very similar to the previous example and will achieve exactly the same result.</p>
|
860
|
+
<div class="code_container">
|
861
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
862
|
+
<%= error_messages_for :product %>
|
863
|
+
</pre>
|
864
|
+
</div>
|
865
|
+
<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>
|
866
|
+
<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, change the header text, change the message below the header, and specify the tag used for the header element. For example,</p>
|
867
|
+
<div class="code_container">
|
868
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
869
|
+
<%= f.error_messages :header_message => "Invalid product!",
|
870
|
+
:message => "You'll need to fix the following fields:",
|
871
|
+
:header_tag => :h3 %>
|
872
|
+
</pre>
|
873
|
+
</div>
|
874
|
+
<p>results in:</p>
|
875
|
+
<p><img src="images/customized_error_messages.png" title="Customized error messages" alt="Customized error messages" /></p>
|
876
|
+
<p>If you pass <tt>nil</tt> in any of these options, the corresponding section of the <tt>div</tt> will be discarded.</p>
|
877
|
+
<h4 id="customizing-error-messages-css">8.4 Customizing the Error Messages <span class="caps">CSS</span></h4>
|
878
|
+
<p>The selectors used to customize the style of error messages are:</p>
|
879
|
+
<ul>
|
880
|
+
<li><tt>.field_with_errors</tt> – Style for the form fields and labels with errors.</li>
|
881
|
+
<li><tt>#error_explanation</tt> – Style for the <tt>div</tt> element with the error messages.</li>
|
882
|
+
<li><tt>#error_explanation h2</tt> – Style for the header of the <tt>div</tt> element.</li>
|
883
|
+
<li><tt>#error_explanation p</tt> – Style for the paragraph holding the message that appears right below the header of the <tt>div</tt> element.</li>
|
884
|
+
<li><tt>#error_explanation ul li</tt> – Style for the list items with individual error messages.</li>
|
885
|
+
</ul>
|
886
|
+
<p>If scaffolding was used, file <tt>app/assets/stylesheets/scaffolds.css.scss</tt> will have been generated automatically. This file defines the red-based styles you saw in the examples above.</p>
|
887
|
+
<p>The name of the class and the id can be changed with the <tt>:class</tt> and <tt>:id</tt> options, accepted by both helpers.</p>
|
888
|
+
<h4 id="customizing-the-error-messages-html">8.5 Customizing the Error Messages <span class="caps">HTML</span></h4>
|
889
|
+
<p>By default, form fields with errors are displayed enclosed by a <tt>div</tt> element with the <tt>field_with_errors</tt> <span class="caps">CSS</span> class. However, it’s possible to override that.</p>
|
890
|
+
<p>The way form fields with errors are treated is defined by <tt>ActionView::Base.field_error_proc</tt>. This is a <tt>Proc</tt> that receives two parameters:</p>
|
891
|
+
<ul>
|
892
|
+
<li>A string with the <span class="caps">HTML</span> tag</li>
|
893
|
+
<li>An instance of <tt>ActionView::Helpers::InstanceTag</tt>.</li>
|
894
|
+
</ul>
|
895
|
+
<p>Below is a simple example where we change the Rails behavior to always display the error messages in front of each of the form fields in error. The error messages will be enclosed by a <tt>span</tt> element with a <tt>validation-error</tt> <span class="caps">CSS</span> 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> <span class="caps">CSS</span> class to style it anyway you want.</p>
|
896
|
+
<div class="code_container">
|
897
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
898
|
+
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
|
899
|
+
if instance.error_message.kind_of?(Array)
|
900
|
+
%(#{html_tag}<span class="validation-error">&nbsp;
|
901
|
+
#{instance.error_message.join(',')}</span>).html_safe
|
902
|
+
else
|
903
|
+
%(#{html_tag}<span class="validation-error">&nbsp;
|
904
|
+
#{instance.error_message}</span>).html_safe
|
905
|
+
end
|
906
|
+
end
|
907
|
+
</pre>
|
908
|
+
</div>
|
909
|
+
<p>The result looks like the following:</p>
|
910
|
+
<p><img src="images/validation_error_messages.png" title="Validation error messages" alt="Validation error messages" /></p>
|
911
|
+
<h3 id="callbacks-overview">9 Callbacks Overview</h3>
|
912
|
+
<p>Callbacks are methods that get called at certain moments of an object’s life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.</p>
|
913
|
+
<h4 id="callback-registration">9.1 Callback Registration</h4>
|
914
|
+
<p>In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks:</p>
|
915
|
+
<div class="code_container">
|
916
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
917
|
+
class User < ActiveRecord::Base
|
918
|
+
validates :login, :email, :presence => true
|
919
|
+
|
920
|
+
before_validation :ensure_login_has_a_value
|
921
|
+
|
922
|
+
protected
|
923
|
+
def ensure_login_has_a_value
|
924
|
+
if login.nil?
|
925
|
+
self.login = email unless email.blank?
|
926
|
+
end
|
927
|
+
end
|
928
|
+
end
|
929
|
+
</pre>
|
930
|
+
</div>
|
931
|
+
<p>The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in a single line:</p>
|
932
|
+
<div class="code_container">
|
933
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
934
|
+
class User < ActiveRecord::Base
|
935
|
+
validates :login, :email, :presence => true
|
936
|
+
|
937
|
+
before_create do |user|
|
938
|
+
user.name = user.login.capitalize if user.name.blank?
|
939
|
+
end
|
940
|
+
end
|
941
|
+
</pre>
|
942
|
+
</div>
|
943
|
+
<p>It is considered good practice to declare callback methods as protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.</p>
|
944
|
+
<h3 id="available-callbacks">10 Available Callbacks</h3>
|
945
|
+
<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>
|
946
|
+
<h4 id="creating-an-object">10.1 Creating an Object</h4>
|
947
|
+
<ul>
|
948
|
+
<li><tt>before_validation</tt></li>
|
949
|
+
<li><tt>after_validation</tt></li>
|
950
|
+
<li><tt>before_save</tt></li>
|
951
|
+
<li><tt>before_create</tt></li>
|
952
|
+
<li><tt>around_create</tt></li>
|
953
|
+
<li><tt>after_create</tt></li>
|
954
|
+
<li><tt>after_save</tt></li>
|
955
|
+
</ul>
|
956
|
+
<h4 id="updating-an-object">10.2 Updating an Object</h4>
|
957
|
+
<ul>
|
958
|
+
<li><tt>before_validation</tt></li>
|
959
|
+
<li><tt>after_validation</tt></li>
|
960
|
+
<li><tt>before_save</tt></li>
|
961
|
+
<li><tt>before_update</tt></li>
|
962
|
+
<li><tt>around_update</tt></li>
|
963
|
+
<li><tt>after_update</tt></li>
|
964
|
+
<li><tt>after_save</tt></li>
|
965
|
+
</ul>
|
966
|
+
<h4 id="destroying-an-object">10.3 Destroying an Object</h4>
|
967
|
+
<ul>
|
968
|
+
<li><tt>before_destroy</tt></li>
|
969
|
+
<li><tt>after_destroy</tt></li>
|
970
|
+
<li><tt>around_destroy</tt></li>
|
971
|
+
</ul>
|
972
|
+
<div class="warning"><p><tt>after_save</tt> runs both on create and update, but always <em>after</em> the more specific callbacks <tt>after_create</tt> and <tt>after_update</tt>, no matter the order in which the macro calls were executed.</p></div>
|
973
|
+
<h4 id="after_initialize-and-after_find">10.4 <tt>after_initialize</tt> and <tt>after_find</tt></h4>
|
974
|
+
<p>The <tt>after_initialize</tt> callback will be called whenever an Active Record object is instantiated, either by directly 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>
|
975
|
+
<p>The <tt>after_find</tt> callback will be called whenever Active Record loads a record from the database. <tt>after_find</tt> is called before <tt>after_initialize</tt> if both are defined.</p>
|
976
|
+
<p>The <tt>after_initialize</tt> and <tt>after_find</tt> callbacks are a bit different from the others. They have no <tt>before_*</tt> counterparts, and they are registered simply by defining them as regular methods with predefined names. 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 behavior 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, which would otherwise significantly slow down the queries.</p>
|
977
|
+
<div class="code_container">
|
978
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
979
|
+
class User < ActiveRecord::Base
|
980
|
+
def after_initialize
|
981
|
+
puts "You have initialized an object!"
|
982
|
+
end
|
983
|
+
|
984
|
+
def after_find
|
985
|
+
puts "You have found an object!"
|
986
|
+
end
|
987
|
+
end
|
988
|
+
|
989
|
+
>> User.new
|
990
|
+
You have initialized an object!
|
991
|
+
=> #<User id: nil>
|
992
|
+
|
993
|
+
>> User.first
|
994
|
+
You have found an object!
|
995
|
+
You have initialized an object!
|
996
|
+
=> #<User id: 1>
|
997
|
+
</pre>
|
998
|
+
</div>
|
999
|
+
<h3 id="running-callbacks">11 Running Callbacks</h3>
|
1000
|
+
<p>The following methods trigger callbacks:</p>
|
1001
|
+
<ul>
|
1002
|
+
<li><tt>create</tt></li>
|
1003
|
+
<li><tt>create!</tt></li>
|
1004
|
+
<li><tt>decrement!</tt></li>
|
1005
|
+
<li><tt>destroy</tt></li>
|
1006
|
+
<li><tt>destroy_all</tt></li>
|
1007
|
+
<li><tt>increment!</tt></li>
|
1008
|
+
<li><tt>save</tt></li>
|
1009
|
+
<li><tt>save!</tt></li>
|
1010
|
+
<li><tt>save(false)</tt></li>
|
1011
|
+
<li><tt>toggle!</tt></li>
|
1012
|
+
<li><tt>update</tt></li>
|
1013
|
+
<li><tt>update_attribute</tt></li>
|
1014
|
+
<li><tt>update_attributes</tt></li>
|
1015
|
+
<li><tt>update_attributes!</tt></li>
|
1016
|
+
<li><tt>valid?</tt></li>
|
1017
|
+
</ul>
|
1018
|
+
<p>Additionally, the <tt>after_find</tt> callback is triggered by the following finder methods:</p>
|
1019
|
+
<ul>
|
1020
|
+
<li><tt>all</tt></li>
|
1021
|
+
<li><tt>first</tt></li>
|
1022
|
+
<li><tt>find</tt></li>
|
1023
|
+
<li><tt>find_all_by_<em>attribute</em></tt></li>
|
1024
|
+
<li><tt>find_by_<em>attribute</em></tt></li>
|
1025
|
+
<li><tt>find_by_<em>attribute</em>!</tt></li>
|
1026
|
+
<li><tt>last</tt></li>
|
1027
|
+
</ul>
|
1028
|
+
<p>The <tt>after_initialize</tt> callback is triggered every time a new object of the class is initialized.</p>
|
1029
|
+
<h3 id="skipping-callbacks">12 Skipping Callbacks</h3>
|
1030
|
+
<p>Just as with validations, it is also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.</p>
|
1031
|
+
<ul>
|
1032
|
+
<li><tt>decrement</tt></li>
|
1033
|
+
<li><tt>decrement_counter</tt></li>
|
1034
|
+
<li><tt>delete</tt></li>
|
1035
|
+
<li><tt>delete_all</tt></li>
|
1036
|
+
<li><tt>find_by_sql</tt></li>
|
1037
|
+
<li><tt>increment</tt></li>
|
1038
|
+
<li><tt>increment_counter</tt></li>
|
1039
|
+
<li><tt>toggle</tt></li>
|
1040
|
+
<li><tt>touch</tt></li>
|
1041
|
+
<li><tt>update_column</tt></li>
|
1042
|
+
<li><tt>update_all</tt></li>
|
1043
|
+
<li><tt>update_counters</tt></li>
|
1044
|
+
</ul>
|
1045
|
+
<h3 id="halting-execution">13 Halting Execution</h3>
|
1046
|
+
<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.</p>
|
1047
|
+
<p>The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly <tt>false</tt> or raises an exception, the execution chain gets halted and a <span class="caps">ROLLBACK</span> is issued; <em>after</em> callbacks can only accomplish that by raising an exception.</p>
|
1048
|
+
<div class="warning"><p>Raising an arbitrary exception may break code that expects <tt>save</tt> and its friends not to fail like that. The <tt>ActiveRecord::Rollback</tt> exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised.</p></div>
|
1049
|
+
<h3 id="relational-callbacks">14 Relational Callbacks</h3>
|
1050
|
+
<p>Callbacks work through model relationships, and can even be defined by them. Suppose an example where a user has many posts. A user’s posts should be destroyed if the user is destroyed. Let’s add an <tt>after_destroy</tt> callback to the <tt>User</tt> model by way of its relationship to the <tt>Post</tt> model:</p>
|
1051
|
+
<div class="code_container">
|
1052
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1053
|
+
class User < ActiveRecord::Base
|
1054
|
+
has_many :posts, :dependent => :destroy
|
1055
|
+
end
|
1056
|
+
|
1057
|
+
class Post < ActiveRecord::Base
|
1058
|
+
after_destroy :log_destroy_action
|
1059
|
+
|
1060
|
+
def log_destroy_action
|
1061
|
+
puts 'Post destroyed'
|
1062
|
+
end
|
1063
|
+
end
|
1064
|
+
|
1065
|
+
>> user = User.first
|
1066
|
+
=> #<User id: 1>
|
1067
|
+
>> user.posts.create!
|
1068
|
+
=> #<Post id: 1, user_id: 1>
|
1069
|
+
>> user.destroy
|
1070
|
+
Post destroyed
|
1071
|
+
=> #<User id: 1>
|
1072
|
+
</pre>
|
1073
|
+
</div>
|
1074
|
+
<h3 id="conditional-callbacks">15 Conditional Callbacks</h3>
|
1075
|
+
<p>As with validations, we can also make the calling of a callback method conditional on the satisfaction of a given predicate. We can do this using the <tt>:if</tt> and <tt>:unless</tt> options, which can take a symbol, a string or a <tt>Proc</tt>. You may use the <tt>:if</tt> option when you want to specify under which conditions the callback <strong>should</strong> be called. If you want to specify the conditions under which the callback <strong>should not</strong> be called, then you may use the <tt>:unless</tt> option.</p>
|
1076
|
+
<h4 id="using-if-and-unless-with-a-symbol">15.1 Using <tt>:if</tt> and <tt>:unless</tt> with a <tt>Symbol</tt></h4>
|
1077
|
+
<p>You can associate the <tt>:if</tt> and <tt>:unless</tt> options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the <tt>:if</tt> option, the callback won’t be executed if the predicate method returns false; when using the <tt>:unless</tt> option, the callback won’t be executed if the predicate method returns true. This is the most common option. Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed.</p>
|
1078
|
+
<div class="code_container">
|
1079
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1080
|
+
class Order < ActiveRecord::Base
|
1081
|
+
before_save :normalize_card_number, :if => :paid_with_card?
|
1082
|
+
end
|
1083
|
+
</pre>
|
1084
|
+
</div>
|
1085
|
+
<h4 id="using-if-and-unless-with-a-string">15.2 Using <tt>:if</tt> and <tt>:unless</tt> with a String</h4>
|
1086
|
+
<p>You can also use a string that will be evaluated using <tt>eval</tt> and hence needs to contain valid Ruby code. You should use this option only when the string represents a really short condition:</p>
|
1087
|
+
<div class="code_container">
|
1088
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1089
|
+
class Order < ActiveRecord::Base
|
1090
|
+
before_save :normalize_card_number, :if => "paid_with_card?"
|
1091
|
+
end
|
1092
|
+
</pre>
|
1093
|
+
</div>
|
1094
|
+
<h4 id="using-if-and-unless-with-a-proc">15.3 Using <tt>:if</tt> and <tt>:unless</tt> with a <tt>Proc</tt></h4>
|
1095
|
+
<p>Finally, it is possible to associate <tt>:if</tt> and <tt>:unless</tt> with a <tt>Proc</tt> object. This option is best suited when writing short validation methods, usually one-liners:</p>
|
1096
|
+
<div class="code_container">
|
1097
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1098
|
+
class Order < ActiveRecord::Base
|
1099
|
+
before_save :normalize_card_number,
|
1100
|
+
:if => Proc.new { |order| order.paid_with_card? }
|
1101
|
+
end
|
1102
|
+
</pre>
|
1103
|
+
</div>
|
1104
|
+
<h4 id="multiple-conditions-for-callbacks">15.4 Multiple Conditions for Callbacks</h4>
|
1105
|
+
<p>When writing conditional callbacks, it is possible to mix both <tt>:if</tt> and <tt>:unless</tt> in the same callback declaration:</p>
|
1106
|
+
<div class="code_container">
|
1107
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1108
|
+
class Comment < ActiveRecord::Base
|
1109
|
+
after_create :send_email_to_author, :if => :author_wants_emails?,
|
1110
|
+
:unless => Proc.new { |comment| comment.post.ignore_comments? }
|
1111
|
+
end
|
1112
|
+
</pre>
|
1113
|
+
</div>
|
1114
|
+
<h3 id="callback-classes">16 Callback Classes</h3>
|
1115
|
+
<p>Sometimes the callback methods that you’ll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.</p>
|
1116
|
+
<p>Here’s an example where we create a class with an <tt>after_destroy</tt> callback for a <tt>PictureFile</tt> model:</p>
|
1117
|
+
<div class="code_container">
|
1118
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1119
|
+
class PictureFileCallbacks
|
1120
|
+
def after_destroy(picture_file)
|
1121
|
+
if File.exists?(picture_file.filepath)
|
1122
|
+
File.delete(picture_file.filepath)
|
1123
|
+
end
|
1124
|
+
end
|
1125
|
+
end
|
1126
|
+
</pre>
|
1127
|
+
</div>
|
1128
|
+
<p>When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:</p>
|
1129
|
+
<div class="code_container">
|
1130
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1131
|
+
class PictureFile < ActiveRecord::Base
|
1132
|
+
after_destroy PictureFileCallbacks.new
|
1133
|
+
end
|
1134
|
+
</pre>
|
1135
|
+
</div>
|
1136
|
+
<p>Note that we needed to instantiate a new <tt>PictureFileCallbacks</tt> object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of the instantiated object. Often, however, it will make more sense to declare the callbacks as class methods:</p>
|
1137
|
+
<div class="code_container">
|
1138
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1139
|
+
class PictureFileCallbacks
|
1140
|
+
def self.after_destroy(picture_file)
|
1141
|
+
if File.exists?(picture_file.filepath)
|
1142
|
+
File.delete(picture_file.filepath)
|
1143
|
+
end
|
1144
|
+
end
|
1145
|
+
end
|
1146
|
+
</pre>
|
1147
|
+
</div>
|
1148
|
+
<p>If the callback method is declared this way, it won’t be necessary to instantiate a <tt>PictureFileCallbacks</tt> object.</p>
|
1149
|
+
<div class="code_container">
|
1150
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1151
|
+
class PictureFile < ActiveRecord::Base
|
1152
|
+
after_destroy PictureFileCallbacks
|
1153
|
+
end
|
1154
|
+
</pre>
|
1155
|
+
</div>
|
1156
|
+
<p>You can declare as many callbacks as you want inside your callback classes.</p>
|
1157
|
+
<h3 id="observers">17 Observers</h3>
|
1158
|
+
<p>Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn’t directly related to its purpose, observers allow you to add the same functionality without changing the code of the model. For example, it could be argued that a <tt>User</tt> model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn’t directly related to your model, you may want to consider creating an observer instead.</p>
|
1159
|
+
<h4 id="creating-observers">17.1 Creating Observers</h4>
|
1160
|
+
<p>For example, imagine a <tt>User</tt> model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model’s purpose, we should create an observer to contain the code implementing this functionality.</p>
|
1161
|
+
<div class="code_container">
|
1162
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
1163
|
+
$ rails generate observer User
|
1164
|
+
</pre>
|
1165
|
+
</div>
|
1166
|
+
<p>generates <tt>app/models/user_observer.rb</tt> containing the observer class <tt>UserObserver</tt>:</p>
|
1167
|
+
<div class="code_container">
|
1168
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1169
|
+
class UserObserver < ActiveRecord::Observer
|
1170
|
+
end
|
1171
|
+
</pre>
|
1172
|
+
</div>
|
1173
|
+
<p>You may now add methods to be called at the desired occasions:</p>
|
1174
|
+
<div class="code_container">
|
1175
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1176
|
+
class UserObserver < ActiveRecord::Observer
|
1177
|
+
def after_create(model)
|
1178
|
+
# code to send confirmation email...
|
1179
|
+
end
|
1180
|
+
end
|
1181
|
+
</pre>
|
1182
|
+
</div>
|
1183
|
+
<p>As with callback classes, the observer’s methods receive the observed model as a parameter.</p>
|
1184
|
+
<h4 id="registering-observers">17.2 Registering Observers</h4>
|
1185
|
+
<p>Observers are conventionally placed inside of your <tt>app/models</tt> directory and registered in your application’s <tt>config/application.rb</tt> file. For example, the <tt>UserObserver</tt> above would be saved as <tt>app/models/user_observer.rb</tt> and registered in <tt>config/application.rb</tt> this way:</p>
|
1186
|
+
<div class="code_container">
|
1187
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1188
|
+
# Activate observers that should always be running.
|
1189
|
+
config.active_record.observers = :user_observer
|
1190
|
+
</pre>
|
1191
|
+
</div>
|
1192
|
+
<p>As usual, settings in <tt>config/environments</tt> take precedence over those in <tt>config/application.rb</tt>. So, if you prefer that an observer doesn’t run in all environments, you can simply register it in a specific environment instead.</p>
|
1193
|
+
<h4 id="sharing-observers">17.3 Sharing Observers</h4>
|
1194
|
+
<p>By default, Rails will simply strip “Observer” from an observer’s name to find the model it should observe. However, observers can also be used to add behavior to more than one model, and thus it is possible to explicitly specify the models that our observer should observe:</p>
|
1195
|
+
<div class="code_container">
|
1196
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1197
|
+
class MailerObserver < ActiveRecord::Observer
|
1198
|
+
observe :registration, :user
|
1199
|
+
|
1200
|
+
def after_create(model)
|
1201
|
+
# code to send confirmation email...
|
1202
|
+
end
|
1203
|
+
end
|
1204
|
+
</pre>
|
1205
|
+
</div>
|
1206
|
+
<p>In this example, the <tt>after_create</tt> method will be called whenever a <tt>Registration</tt> or <tt>User</tt> is created. Note that this new <tt>MailerObserver</tt> would also need to be registered in <tt>config/application.rb</tt> in order to take effect:</p>
|
1207
|
+
<div class="code_container">
|
1208
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1209
|
+
# Activate observers that should always be running.
|
1210
|
+
config.active_record.observers = :mailer_observer
|
1211
|
+
</pre>
|
1212
|
+
</div>
|
1213
|
+
<h3 id="transaction-callbacks">18 Transaction Callbacks</h3>
|
1214
|
+
<p>There are two additional callbacks that are triggered by the completion of a database transaction: <tt>after_commit</tt> and <tt>after_rollback</tt>. These callbacks are very similar to the <tt>after_save</tt> callback except that they don’t execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction.</p>
|
1215
|
+
<p>Consider, for example, the previous example where the <tt>PictureFile</tt> model needs to delete a file after the corresponding record is destroyed. If anything raises an exception after the <tt>after_destroy</tt> callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that <tt>picture_file_2</tt> in the code below is not valid and the <tt>save!</tt> method raises an error.</p>
|
1216
|
+
<div class="code_container">
|
1217
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1218
|
+
PictureFile.transaction do
|
1219
|
+
picture_file_1.destroy
|
1220
|
+
picture_file_2.save!
|
1221
|
+
end
|
1222
|
+
</pre>
|
1223
|
+
</div>
|
1224
|
+
<p>By using the <tt>after_commit</tt> callback we can account for this case.</p>
|
1225
|
+
<div class="code_container">
|
1226
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1227
|
+
class PictureFile < ActiveRecord::Base
|
1228
|
+
attr_accessor :delete_file
|
1229
|
+
|
1230
|
+
after_destroy do |picture_file|
|
1231
|
+
picture_file.delete_file = picture_file.filepath
|
1232
|
+
end
|
1233
|
+
|
1234
|
+
after_commit do |picture_file|
|
1235
|
+
if picture_file.delete_file && File.exist?(picture_file.delete_file)
|
1236
|
+
File.delete(picture_file.delete_file)
|
1237
|
+
picture_file.delete_file = nil
|
1238
|
+
end
|
1239
|
+
end
|
1240
|
+
end
|
1241
|
+
</pre>
|
1242
|
+
</div>
|
1243
|
+
<p>The <tt>after_commit</tt> and <tt>after_rollback</tt> callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don’t interfere with the other callbacks. As such, if your callback code could raise an exception, you’ll need to rescue it and handle it appropriately within the callback.</p>
|
1244
|
+
|
1245
|
+
<h3>Feedback</h3>
|
1246
|
+
<p>
|
1247
|
+
You're encouraged to help improve the quality of this guide.
|
1248
|
+
</p>
|
1249
|
+
<p>
|
1250
|
+
If you see any typos or factual errors you are confident to
|
1251
|
+
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
|
1252
|
+
and push the change yourself. That branch of Rails has public write access.
|
1253
|
+
Commits are still reviewed, but that happens after you've submitted your
|
1254
|
+
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
|
1255
|
+
cross-merged with master periodically.
|
1256
|
+
</p>
|
1257
|
+
<p>
|
1258
|
+
You may also find incomplete content, or stuff that is not up to date.
|
1259
|
+
Please do add any missing documentation for master. Check the
|
1260
|
+
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
|
1261
|
+
for style and conventions.
|
1262
|
+
</p>
|
1263
|
+
<p>
|
1264
|
+
If for whatever reason you spot something to fix but cannot patch it yourself, please
|
1265
|
+
<a href="https://github.com/rails/rails/issues">open an issue</a>.
|
1266
|
+
</p>
|
1267
|
+
<p>And last but not least, any kind of discussion regarding Ruby on Rails
|
1268
|
+
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
|
1269
|
+
</p>
|
1270
|
+
</div>
|
1271
|
+
</div>
|
1272
|
+
</div>
|
1273
|
+
|
1274
|
+
<hr class="hide" />
|
1275
|
+
<div id="footer">
|
1276
|
+
<div class="wrapper">
|
1277
|
+
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
|
1278
|
+
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
|
1279
|
+
</div>
|
1280
|
+
</div>
|
1281
|
+
|
1282
|
+
<script type="text/javascript" src="javascripts/guides.js"></script>
|
1283
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
|
1284
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
|
1285
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
|
1286
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
|
1287
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
|
1288
|
+
<script type="text/javascript">
|
1289
|
+
SyntaxHighlighter.all()
|
1290
|
+
</script>
|
1291
|
+
</body>
|
1292
|
+
</html>
|