rails 4.2.0.beta4 → 4.2.0.rc1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (230) hide show
  1. checksums.yaml +4 -4
  2. data/guides/Rakefile +3 -1
  3. data/guides/bug_report_templates/action_controller_gem.rb +2 -2
  4. data/guides/bug_report_templates/action_controller_master.rb +2 -2
  5. data/guides/source/3_0_release_notes.md +2 -2
  6. data/guides/source/4_1_release_notes.md +1 -1
  7. data/guides/source/4_2_release_notes.md +250 -225
  8. data/guides/source/_welcome.html.erb +1 -1
  9. data/guides/source/action_controller_overview.md +6 -6
  10. data/guides/source/action_mailer_basics.md +26 -11
  11. data/guides/source/action_view_overview.md +0 -1
  12. data/guides/source/active_job_basics.md +29 -23
  13. data/guides/source/active_record_postgresql.md +2 -7
  14. data/guides/source/active_record_validations.md +1 -0
  15. data/guides/source/active_support_core_extensions.md +1 -1
  16. data/guides/source/active_support_instrumentation.md +5 -5
  17. data/guides/source/asset_pipeline.md +2 -2
  18. data/guides/source/association_basics.md +0 -2
  19. data/guides/source/command_line.md +6 -15
  20. data/guides/source/configuring.md +4 -4
  21. data/guides/source/documents.yaml +0 -1
  22. data/guides/source/engines.md +26 -15
  23. data/guides/source/form_helpers.md +10 -2
  24. data/guides/source/getting_started.md +9 -9
  25. data/guides/source/rails_on_rack.md +2 -2
  26. data/guides/source/ruby_on_rails_guides_guidelines.md +1 -0
  27. data/guides/source/security.md +1 -1
  28. data/guides/source/testing.md +80 -13
  29. data/guides/source/upgrading_ruby_on_rails.md +23 -20
  30. metadata +29 -229
  31. data/guides/output/2_2_release_notes.html +0 -724
  32. data/guides/output/2_3_release_notes.html +0 -870
  33. data/guides/output/3_0_release_notes.html +0 -773
  34. data/guides/output/3_1_release_notes.html +0 -740
  35. data/guides/output/3_2_release_notes.html +0 -797
  36. data/guides/output/4_0_release_notes.html +0 -523
  37. data/guides/output/4_1_release_notes.html +0 -806
  38. data/guides/output/4_2_release_notes.html +0 -728
  39. data/guides/output/Gemfile +0 -6
  40. data/guides/output/_license.html +0 -226
  41. data/guides/output/_welcome.html +0 -233
  42. data/guides/output/action_controller_overview.html +0 -1335
  43. data/guides/output/action_mailer_basics.html +0 -928
  44. data/guides/output/action_view_overview.html +0 -1509
  45. data/guides/output/active_job_basics.html +0 -546
  46. data/guides/output/active_model_basics.html +0 -438
  47. data/guides/output/active_record_basics.html +0 -594
  48. data/guides/output/active_record_callbacks.html +0 -592
  49. data/guides/output/active_record_migrations.html +0 -1123
  50. data/guides/output/active_record_postgresql.html +0 -675
  51. data/guides/output/active_record_querying.html +0 -1796
  52. data/guides/output/active_record_validations.html +0 -1301
  53. data/guides/output/active_support_core_extensions.html +0 -3450
  54. data/guides/output/active_support_instrumentation.html +0 -1121
  55. data/guides/output/api_documentation_guidelines.html +0 -498
  56. data/guides/output/asset_pipeline.html +0 -1167
  57. data/guides/output/association_basics.html +0 -2086
  58. data/guides/output/caching_with_rails.html +0 -553
  59. data/guides/output/command_line.html +0 -791
  60. data/guides/output/configuring.html +0 -1055
  61. data/guides/output/contributing_to_ruby_on_rails.html +0 -657
  62. data/guides/output/credits.html +0 -284
  63. data/guides/output/debugging_rails_applications.html +0 -1014
  64. data/guides/output/development_dependencies_install.html +0 -478
  65. data/guides/output/engines.html +0 -1438
  66. data/guides/output/form_helpers.html +0 -1074
  67. data/guides/output/generators.html +0 -838
  68. data/guides/output/getting_started.html +0 -2092
  69. data/guides/output/i18n.html +0 -1198
  70. data/guides/output/images/akshaysurve.jpg +0 -0
  71. data/guides/output/images/belongs_to.png +0 -0
  72. data/guides/output/images/book_icon.gif +0 -0
  73. data/guides/output/images/bullet.gif +0 -0
  74. data/guides/output/images/chapters_icon.gif +0 -0
  75. data/guides/output/images/check_bullet.gif +0 -0
  76. data/guides/output/images/credits_pic_blank.gif +0 -0
  77. data/guides/output/images/csrf.png +0 -0
  78. data/guides/output/images/edge_badge.png +0 -0
  79. data/guides/output/images/favicon.ico +0 -0
  80. data/guides/output/images/feature_tile.gif +0 -0
  81. data/guides/output/images/footer_tile.gif +0 -0
  82. data/guides/output/images/fxn.png +0 -0
  83. data/guides/output/images/getting_started/article_with_comments.png +0 -0
  84. data/guides/output/images/getting_started/challenge.png +0 -0
  85. data/guides/output/images/getting_started/confirm_dialog.png +0 -0
  86. data/guides/output/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  87. data/guides/output/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  88. data/guides/output/images/getting_started/form_with_errors.png +0 -0
  89. data/guides/output/images/getting_started/index_action_with_edit_link.png +0 -0
  90. data/guides/output/images/getting_started/new_article.png +0 -0
  91. data/guides/output/images/getting_started/new_post.png +0 -0
  92. data/guides/output/images/getting_started/post_with_comments.png +0 -0
  93. data/guides/output/images/getting_started/rails_welcome.png +0 -0
  94. data/guides/output/images/getting_started/routing_error_no_controller.png +0 -0
  95. data/guides/output/images/getting_started/routing_error_no_route_matches.png +0 -0
  96. data/guides/output/images/getting_started/show_action_for_articles.png +0 -0
  97. data/guides/output/images/getting_started/show_action_for_posts.png +0 -0
  98. data/guides/output/images/getting_started/template_is_missing_articles_new.png +0 -0
  99. data/guides/output/images/getting_started/template_is_missing_posts_new.png +0 -0
  100. data/guides/output/images/getting_started/undefined_method_post_path.png +0 -0
  101. data/guides/output/images/getting_started/unknown_action_create_for_articles.png +0 -0
  102. data/guides/output/images/getting_started/unknown_action_create_for_posts.png +0 -0
  103. data/guides/output/images/getting_started/unknown_action_new_for_articles.png +0 -0
  104. data/guides/output/images/getting_started/unknown_action_new_for_posts.png +0 -0
  105. data/guides/output/images/grey_bullet.gif +0 -0
  106. data/guides/output/images/habtm.png +0 -0
  107. data/guides/output/images/has_many.png +0 -0
  108. data/guides/output/images/has_many_through.png +0 -0
  109. data/guides/output/images/has_one.png +0 -0
  110. data/guides/output/images/has_one_through.png +0 -0
  111. data/guides/output/images/header_backdrop.png +0 -0
  112. data/guides/output/images/header_tile.gif +0 -0
  113. data/guides/output/images/i18n/demo_html_safe.png +0 -0
  114. data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
  115. data/guides/output/images/i18n/demo_translated_en.png +0 -0
  116. data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
  117. data/guides/output/images/i18n/demo_translation_missing.png +0 -0
  118. data/guides/output/images/i18n/demo_untranslated.png +0 -0
  119. data/guides/output/images/icons/README +0 -5
  120. data/guides/output/images/icons/callouts/1.png +0 -0
  121. data/guides/output/images/icons/callouts/10.png +0 -0
  122. data/guides/output/images/icons/callouts/11.png +0 -0
  123. data/guides/output/images/icons/callouts/12.png +0 -0
  124. data/guides/output/images/icons/callouts/13.png +0 -0
  125. data/guides/output/images/icons/callouts/14.png +0 -0
  126. data/guides/output/images/icons/callouts/15.png +0 -0
  127. data/guides/output/images/icons/callouts/2.png +0 -0
  128. data/guides/output/images/icons/callouts/3.png +0 -0
  129. data/guides/output/images/icons/callouts/4.png +0 -0
  130. data/guides/output/images/icons/callouts/5.png +0 -0
  131. data/guides/output/images/icons/callouts/6.png +0 -0
  132. data/guides/output/images/icons/callouts/7.png +0 -0
  133. data/guides/output/images/icons/callouts/8.png +0 -0
  134. data/guides/output/images/icons/callouts/9.png +0 -0
  135. data/guides/output/images/icons/caution.png +0 -0
  136. data/guides/output/images/icons/example.png +0 -0
  137. data/guides/output/images/icons/home.png +0 -0
  138. data/guides/output/images/icons/important.png +0 -0
  139. data/guides/output/images/icons/next.png +0 -0
  140. data/guides/output/images/icons/note.png +0 -0
  141. data/guides/output/images/icons/prev.png +0 -0
  142. data/guides/output/images/icons/tip.png +0 -0
  143. data/guides/output/images/icons/up.png +0 -0
  144. data/guides/output/images/icons/warning.png +0 -0
  145. data/guides/output/images/nav_arrow.gif +0 -0
  146. data/guides/output/images/oscardelben.jpg +0 -0
  147. data/guides/output/images/polymorphic.png +0 -0
  148. data/guides/output/images/radar.png +0 -0
  149. data/guides/output/images/rails4_features.png +0 -0
  150. data/guides/output/images/rails_guides_kindle_cover.jpg +0 -0
  151. data/guides/output/images/rails_guides_logo.gif +0 -0
  152. data/guides/output/images/rails_logo_remix.gif +0 -0
  153. data/guides/output/images/session_fixation.png +0 -0
  154. data/guides/output/images/tab_grey.gif +0 -0
  155. data/guides/output/images/tab_info.gif +0 -0
  156. data/guides/output/images/tab_note.gif +0 -0
  157. data/guides/output/images/tab_red.gif +0 -0
  158. data/guides/output/images/tab_yellow.gif +0 -0
  159. data/guides/output/images/tab_yellow.png +0 -0
  160. data/guides/output/images/vijaydev.jpg +0 -0
  161. data/guides/output/index.html +0 -354
  162. data/guides/output/initialization.html +0 -876
  163. data/guides/output/javascripts/guides.js +0 -59
  164. data/guides/output/javascripts/jquery.min.js +0 -4
  165. data/guides/output/javascripts/responsive-tables.js +0 -43
  166. data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  167. data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  168. data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  169. data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  170. data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  171. data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  172. data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  173. data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  174. data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  175. data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  176. data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  177. data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  178. data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  179. data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  180. data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  181. data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  182. data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  183. data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  184. data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  185. data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  186. data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  187. data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  188. data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  189. data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  190. data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  191. data/guides/output/javascripts/syntaxhighlighter/shCore.js +0 -17
  192. data/guides/output/layout.html +0 -448
  193. data/guides/output/layouts_and_rendering.html +0 -1541
  194. data/guides/output/maintenance_policy.html +0 -257
  195. data/guides/output/migrations.html +0 -1360
  196. data/guides/output/nested_model_forms.html +0 -412
  197. data/guides/output/plugins.html +0 -644
  198. data/guides/output/rails_application_templates.html +0 -450
  199. data/guides/output/rails_on_rack.html +0 -547
  200. data/guides/output/routing.html +0 -1631
  201. data/guides/output/ruby_on_rails_guides_guidelines.html +0 -329
  202. data/guides/output/security.html +0 -935
  203. data/guides/output/stylesheets/fixes.css +0 -16
  204. data/guides/output/stylesheets/kindle.css +0 -11
  205. data/guides/output/stylesheets/main.css +0 -713
  206. data/guides/output/stylesheets/print.css +0 -52
  207. data/guides/output/stylesheets/reset.css +0 -43
  208. data/guides/output/stylesheets/responsive-tables.css +0 -50
  209. data/guides/output/stylesheets/style.css +0 -13
  210. data/guides/output/stylesheets/syntaxhighlighter/shCore.css +0 -226
  211. data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  212. data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  213. data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  214. data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  215. data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  216. data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  217. data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  218. data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  219. data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  220. data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  221. data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  222. data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  223. data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  224. data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  225. data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  226. data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  227. data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  228. data/guides/output/testing.html +0 -1350
  229. data/guides/output/upgrading_ruby_on_rails.html +0 -1135
  230. data/guides/output/working_with_javascript_in_rails.html +0 -587
@@ -1,1301 +0,0 @@
1
- <!DOCTYPE html>
2
-
3
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4
- <head>
5
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
6
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
7
-
8
- <title>Active Record Validations — Ruby on Rails Guides</title>
9
- <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
10
- <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
11
-
12
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
13
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
14
-
15
- <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
16
-
17
- <link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
18
- </head>
19
- <body class="guide">
20
- <div id="topNav">
21
- <div class="wrapper">
22
- <strong class="more-info-label">More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
23
- <span class="red-button more-info-button">
24
- More Ruby on Rails
25
- </span>
26
- <ul class="more-info-links s-hidden">
27
- <li class="more-info"><a href="http://rubyonrails.org/">Overview</a></li>
28
- <li class="more-info"><a href="http://rubyonrails.org/download">Download</a></li>
29
- <li class="more-info"><a href="http://rubyonrails.org/deploy">Deploy</a></li>
30
- <li class="more-info"><a href="https://github.com/rails/rails">Code</a></li>
31
- <li class="more-info"><a href="http://rubyonrails.org/screencasts">Screencasts</a></li>
32
- <li class="more-info"><a href="http://rubyonrails.org/documentation">Documentation</a></li>
33
- <li class="more-info"><a href="http://rubyonrails.org/community">Community</a></li>
34
- <li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
35
- </ul>
36
- </div>
37
- </div>
38
- <div id="header">
39
- <div class="wrapper clearfix">
40
- <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
41
- <ul class="nav">
42
- <li><a class="nav-item" href="index.html">Home</a></li>
43
- <li class="guides-index guides-index-large">
44
- <a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Guides Index</a>
45
- <div id="guides" class="clearfix" style="display: none;">
46
- <hr />
47
- <dl class="L">
48
- <dt>Start Here</dt>
49
- <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
50
- <dt>Models</dt>
51
- <dd><a href="active_record_basics.html">Active Record Basics</a></dd>
52
- <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd>
53
- <dd><a href="active_record_validations.html">Active Record Validations</a></dd>
54
- <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd>
55
- <dd><a href="association_basics.html">Active Record Associations</a></dd>
56
- <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
57
- <dt>Views</dt>
58
- <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
59
- <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
60
- <dt>Controllers</dt>
61
- <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
62
- <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
63
- </dl>
64
- <dl class="R">
65
- <dt>Digging Deeper</dt>
66
- <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
67
- <dd><a href="i18n.html">Rails Internationalization API</a></dd>
68
- <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
69
- <dd><a href="active_job_basics.html">Active Job Basics</a></dd>
70
- <dd><a href="security.html">Securing Rails Applications</a></dd>
71
- <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
72
- <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
73
- <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
74
- <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
75
- <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
76
- <dt>Extending Rails</dt>
77
- <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
78
- <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
79
- <dt>Contributing to Ruby on Rails</dt>
80
- <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
81
- <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
82
- <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
83
- <dt>Maintenance Policy</dt>
84
- <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
85
- <dt>Release Notes</dt>
86
- <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
87
- <dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</a></dd>
88
- <dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</a></dd>
89
- <dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</a></dd>
90
- <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
91
- <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
92
- <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
93
- <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
94
- </dl>
95
- </div>
96
- </li>
97
- <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li>
98
- <li><a class="nav-item" href="credits.html">Credits</a></li>
99
- <li class="guides-index guides-index-small">
100
- <select class="guides-index-item nav-item">
101
- <option value="index.html">Guides Index</option>
102
- <optgroup label="Start Here">
103
- <option value="getting_started.html">Getting Started with Rails</option>
104
- </optgroup>
105
- <optgroup label="Models">
106
- <option value="active_record_basics.html">Active Record Basics</option>
107
- <option value="active_record_migrations.html">Active Record Migrations</option>
108
- <option value="active_record_validations.html">Active Record Validations</option>
109
- <option value="active_record_callbacks.html">Active Record Callbacks</option>
110
- <option value="association_basics.html">Active Record Associations</option>
111
- <option value="active_record_querying.html">Active Record Query Interface</option>
112
- </optgroup>
113
- <optgroup label="Views">
114
- <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
115
- <option value="form_helpers.html">Action View Form Helpers</option>
116
- </optgroup>
117
- <optgroup label="Controllers">
118
- <option value="action_controller_overview.html">Action Controller Overview</option>
119
- <option value="routing.html">Rails Routing from the Outside In</option>
120
- </optgroup>
121
- <optgroup label="Digging Deeper">
122
- <option value="active_support_core_extensions.html">Active Support Core Extensions</option>
123
- <option value="i18n.html">Rails Internationalization API</option>
124
- <option value="action_mailer_basics.html">Action Mailer Basics</option>
125
- <option value="active_job_basics.html">Active Job Basics</option>
126
- <option value="security.html">Securing Rails Applications</option>
127
- <option value="debugging_rails_applications.html">Debugging Rails Applications</option>
128
- <option value="configuring.html">Configuring Rails Applications</option>
129
- <option value="command_line.html">Rails Command Line Tools and Rake Tasks</option>
130
- <option value="asset_pipeline.html">Asset Pipeline</option>
131
- <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
132
- </optgroup>
133
- <optgroup label="Extending Rails">
134
- <option value="rails_on_rack.html">Rails on Rack</option>
135
- <option value="generators.html">Creating and Customizing Rails Generators</option>
136
- </optgroup>
137
- <optgroup label="Contributing to Ruby on Rails">
138
- <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
139
- <option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
140
- <option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</option>
141
- </optgroup>
142
- <optgroup label="Maintenance Policy">
143
- <option value="maintenance_policy.html">Maintenance Policy</option>
144
- </optgroup>
145
- <optgroup label="Release Notes">
146
- <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
147
- <option value="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</option>
148
- <option value="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</option>
149
- <option value="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</option>
150
- <option value="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</option>
151
- <option value="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</option>
152
- <option value="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</option>
153
- <option value="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</option>
154
- </optgroup>
155
- </select>
156
- </li>
157
- </ul>
158
- </div>
159
- </div>
160
- <hr class="hide" />
161
-
162
- <div id="feature">
163
- <div class="wrapper">
164
- <h2>Active Record Validations</h2><p>This guide teaches you how to validate the state of objects before they go into
165
- the database using Active Record&#39;s validations feature.</p><p>After reading this guide, you will know:</p>
166
- <ul>
167
- <li>How to use the built-in Active Record validation helpers.</li>
168
- <li>How to create your own custom validation methods.</li>
169
- <li>How to work with the error messages generated by the validation process.</li>
170
- </ul>
171
-
172
-
173
- <div id="subCol">
174
- <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
175
- <ol class="chapters">
176
- <li>
177
- <a href="#validations-overview">Validations Overview</a>
178
-
179
- <ul>
180
- <li><a href="#why-use-validations-questionmark">Why Use Validations?</a></li>
181
- <li><a href="#when-does-validation-happen-questionmark">When Does Validation Happen?</a></li>
182
- <li><a href="#skipping-validations">Skipping Validations</a></li>
183
- <li><a href="#valid-questionmark-and-invalid-questionmark"><code>valid?</code> and <code>invalid?</code></a></li>
184
- <li><a href="#validations-overview-errors%5B%5D"><code>errors[]</code></a></li>
185
- </ul>
186
- </li>
187
- <li>
188
- <a href="#validation-helpers">Validation Helpers</a>
189
-
190
- <ul>
191
- <li><a href="#acceptance"><code>acceptance</code></a></li>
192
- <li><a href="#validates_associated"><code>validates_associated</code></a></li>
193
- <li><a href="#confirmation"><code>confirmation</code></a></li>
194
- <li><a href="#exclusion"><code>exclusion</code></a></li>
195
- <li><a href="#format"><code>format</code></a></li>
196
- <li><a href="#inclusion"><code>inclusion</code></a></li>
197
- <li><a href="#length"><code>length</code></a></li>
198
- <li><a href="#numericality"><code>numericality</code></a></li>
199
- <li><a href="#presence"><code>presence</code></a></li>
200
- <li><a href="#absence"><code>absence</code></a></li>
201
- <li><a href="#uniqueness"><code>uniqueness</code></a></li>
202
- <li><a href="#validates_with"><code>validates_with</code></a></li>
203
- <li><a href="#validates_each"><code>validates_each</code></a></li>
204
- </ul>
205
- </li>
206
- <li>
207
- <a href="#common-validation-options">Common Validation Options</a>
208
-
209
- <ul>
210
- <li><a href="#:allow_nil"><code>:allow_nil</code></a></li>
211
- <li><a href="#:allow_blank"><code>:allow_blank</code></a></li>
212
- <li><a href="#:message"><code>:message</code></a></li>
213
- <li><a href="#:on"><code>:on</code></a></li>
214
- </ul>
215
- </li>
216
- <li><a href="#strict-validations">Strict Validations</a></li>
217
- <li>
218
- <a href="#conditional-validation">Conditional Validation</a>
219
-
220
- <ul>
221
- <li><a href="#using-a-symbol-with-:if-and-:unless">Using a Symbol with <code>:if</code> and <code>:unless</code></a></li>
222
- <li><a href="#using-a-string-with-:if-and-:unless">Using a String with <code>:if</code> and <code>:unless</code></a></li>
223
- <li><a href="#using-a-proc-with-:if-and-:unless">Using a Proc with <code>:if</code> and <code>:unless</code></a></li>
224
- <li><a href="#grouping-conditional-validations">Grouping Conditional validations</a></li>
225
- <li><a href="#combining-validation-conditions">Combining Validation Conditions</a></li>
226
- </ul>
227
- </li>
228
- <li>
229
- <a href="#performing-custom-validations">Performing Custom Validations</a>
230
-
231
- <ul>
232
- <li><a href="#custom-validators">Custom Validators</a></li>
233
- <li><a href="#custom-methods">Custom Methods</a></li>
234
- </ul>
235
- </li>
236
- <li>
237
- <a href="#working-with-validation-errors">Working with Validation Errors</a>
238
-
239
- <ul>
240
- <li><a href="#errors"><code>errors</code></a></li>
241
- <li><a href="#working-with-validation-errors-errors%5B%5D"><code>errors[]</code></a></li>
242
- <li><a href="#errors.add"><code>errors.add</code></a></li>
243
- <li><a href="#errors%5B:base%5D"><code>errors[:base]</code></a></li>
244
- <li><a href="#errors.clear"><code>errors.clear</code></a></li>
245
- <li><a href="#errors.size"><code>errors.size</code></a></li>
246
- </ul>
247
- </li>
248
- <li><a href="#displaying-validation-errors-in-views">Displaying Validation Errors in Views</a></li>
249
- </ol>
250
-
251
- </div>
252
-
253
- </div>
254
- </div>
255
-
256
- <div id="container">
257
- <div class="wrapper">
258
- <div id="mainCol">
259
- <h3 id="validations-overview">1 Validations Overview</h3><p>Here's an example of a very simple validation:</p><div class="code_container">
260
- <pre class="brush: ruby; gutter: false; toolbar: false">
261
- class Person &lt; ActiveRecord::Base
262
- validates :name, presence: true
263
- end
264
-
265
- Person.create(name: "John Doe").valid? # =&gt; true
266
- Person.create(name: nil).valid? # =&gt; false
267
-
268
- </pre>
269
- </div>
270
- <p>As you can see, our validation lets us know that our <code>Person</code> is not valid
271
- without a <code>name</code> attribute. The second <code>Person</code> will not be persisted to the
272
- database.</p><p>Before we dig into more details, let's talk about how validations fit into the
273
- big picture of your application.</p><h4 id="why-use-validations-questionmark">1.1 Why Use Validations?</h4><p>Validations are used to ensure that only valid data is saved into your
274
- database. For example, it may be important to your application to ensure that
275
- every user provides a valid email address and mailing address. Model-level
276
- validations are the best way to ensure that only valid data is saved into your
277
- database. They are database agnostic, cannot be bypassed by end users, and are
278
- convenient to test and maintain. Rails makes them easy to use, provides
279
- built-in helpers for common needs, and allows you to create your own validation
280
- methods as well.</p><p>There are several other ways to validate data before it is saved into your
281
- database, including native database constraints, client-side validations,
282
- controller-level validations. Here's a summary of the pros and cons:</p>
283
- <ul>
284
- <li>Database constraints and/or stored procedures make the validation mechanisms
285
- database-dependent and can make testing and maintenance more difficult.
286
- However, if your database is used by other applications, it may be a good
287
- idea to use some constraints at the database level. Additionally,
288
- database-level validations can safely handle some things (such as uniqueness
289
- in heavily-used tables) that can be difficult to implement otherwise.</li>
290
- <li>Client-side validations can be useful, but are generally unreliable if used
291
- alone. If they are implemented using JavaScript, they may be bypassed if
292
- JavaScript is turned off in the user's browser. However, if combined with
293
- other techniques, client-side validation can be a convenient way to provide
294
- users with immediate feedback as they use your site.</li>
295
- <li>Controller-level validations can be tempting to use, but often become
296
- unwieldy and difficult to test and maintain. Whenever possible, it's a good
297
- idea to keep your controllers skinny, as it will make your application a
298
- pleasure to work with in the long run.</li>
299
- </ul>
300
- <p>Choose these in certain, specific cases. It's the opinion of the Rails team
301
- that model-level validations are the most appropriate in most circumstances.</p><h4 id="when-does-validation-happen-questionmark">1.2 When Does Validation Happen?</h4><p>There are two kinds of Active Record objects: those that correspond to a row
302
- inside your database and those that do not. When you create a fresh object, for
303
- example using the <code>new</code> method, that object does not belong to the database
304
- yet. Once you call <code>save</code> upon that object it will be saved into the
305
- appropriate database table. Active Record uses the <code>new_record?</code> instance
306
- method to determine whether an object is already in the database or not.
307
- Consider the following simple Active Record class:</p><div class="code_container">
308
- <pre class="brush: ruby; gutter: false; toolbar: false">
309
- class Person &lt; ActiveRecord::Base
310
- end
311
-
312
- </pre>
313
- </div>
314
- <p>We can see how it works by looking at some <code>rails console</code> output:</p><div class="code_container">
315
- <pre class="brush: ruby; gutter: false; toolbar: false">
316
- $ bin/rails console
317
- &gt;&gt; p = Person.new(name: "John Doe")
318
- =&gt; #&lt;Person id: nil, name: "John Doe", created_at: nil, updated_at: nil&gt;
319
- &gt;&gt; p.new_record?
320
- =&gt; true
321
- &gt;&gt; p.save
322
- =&gt; true
323
- &gt;&gt; p.new_record?
324
- =&gt; false
325
-
326
- </pre>
327
- </div>
328
- <p>Creating and saving a new record will send an SQL <code>INSERT</code> operation to the
329
- database. Updating an existing record will send an SQL <code>UPDATE</code> operation
330
- instead. Validations are typically run before these commands are sent to the
331
- database. If any validations fail, the object will be marked as invalid and
332
- Active Record will not perform the <code>INSERT</code> or <code>UPDATE</code> operation. This avoids
333
- storing an invalid object in the database. You can choose to have specific
334
- validations run when an object is created, saved, or updated.</p><div class="warning"><p>There are many ways to change the state of an object in the database.
335
- Some methods will trigger validations, but some will not. This means that it's
336
- possible to save an object in the database in an invalid state if you aren't
337
- careful.</p></div><p>The following methods trigger validations, and will save the object to the
338
- database only if the object is valid:</p>
339
- <ul>
340
- <li><code>create</code></li>
341
- <li><code>create!</code></li>
342
- <li><code>save</code></li>
343
- <li><code>save!</code></li>
344
- <li><code>update</code></li>
345
- <li><code>update!</code></li>
346
- </ul>
347
- <p>The bang versions (e.g. <code>save!</code>) raise an exception if the record is invalid.
348
- The non-bang versions don't, <code>save</code> and <code>update</code> return <code>false</code>,
349
- <code>create</code> just returns the object.</p><h4 id="skipping-validations">1.3 Skipping Validations</h4><p>The following methods skip validations, and will save the object to the
350
- database regardless of its validity. They should be used with caution.</p>
351
- <ul>
352
- <li><code>decrement!</code></li>
353
- <li><code>decrement_counter</code></li>
354
- <li><code>increment!</code></li>
355
- <li><code>increment_counter</code></li>
356
- <li><code>toggle!</code></li>
357
- <li><code>touch</code></li>
358
- <li><code>update_all</code></li>
359
- <li><code>update_attribute</code></li>
360
- <li><code>update_column</code></li>
361
- <li><code>update_columns</code></li>
362
- <li><code>update_counters</code></li>
363
- </ul>
364
- <p>Note that <code>save</code> also has the ability to skip validations if passed <code>validate:
365
- false</code> as argument. This technique should be used with caution.</p>
366
- <ul>
367
- <li><code>save(validate: false)</code></li>
368
- </ul>
369
- <h4 id="valid-questionmark-and-invalid-questionmark">1.4 <code>valid?</code> and <code>invalid?</code>
370
- </h4><p>To verify whether or not an object is valid, Rails uses the <code>valid?</code> method.
371
- You can also use this method on your own. <code>valid?</code> triggers your validations
372
- and returns true if no errors were found in the object, and false otherwise.
373
- As you saw above:</p><div class="code_container">
374
- <pre class="brush: ruby; gutter: false; toolbar: false">
375
- class Person &lt; ActiveRecord::Base
376
- validates :name, presence: true
377
- end
378
-
379
- Person.create(name: "John Doe").valid? # =&gt; true
380
- Person.create(name: nil).valid? # =&gt; false
381
-
382
- </pre>
383
- </div>
384
- <p>After Active Record has performed validations, any errors found can be accessed
385
- through the <code>errors.messages</code> instance method, which returns a collection of errors.
386
- By definition, an object is valid if this collection is empty after running
387
- validations.</p><p>Note that an object instantiated with <code>new</code> will not report errors even if it's
388
- technically invalid, because validations are not run when using <code>new</code>.</p><div class="code_container">
389
- <pre class="brush: ruby; gutter: false; toolbar: false">
390
- class Person &lt; ActiveRecord::Base
391
- validates :name, presence: true
392
- end
393
-
394
- &gt;&gt; p = Person.new
395
- # =&gt; #&lt;Person id: nil, name: nil&gt;
396
- &gt;&gt; p.errors.messages
397
- # =&gt; {}
398
-
399
- &gt;&gt; p.valid?
400
- # =&gt; false
401
- &gt;&gt; p.errors.messages
402
- # =&gt; {name:["can't be blank"]}
403
-
404
- &gt;&gt; p = Person.create
405
- # =&gt; #&lt;Person id: nil, name: nil&gt;
406
- &gt;&gt; p.errors.messages
407
- # =&gt; {name:["can't be blank"]}
408
-
409
- &gt;&gt; p.save
410
- # =&gt; false
411
-
412
- &gt;&gt; p.save!
413
- # =&gt; ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
414
-
415
- &gt;&gt; Person.create!
416
- # =&gt; ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
417
-
418
- </pre>
419
- </div>
420
- <p><code>invalid?</code> is simply the inverse of <code>valid?</code>. It triggers your validations,
421
- returning true if any errors were found in the object, and false otherwise.</p><h4 id="validations-overview-errors[]">1.5 <code>errors[]</code>
422
- </h4><p>To verify whether or not a particular attribute of an object is valid, you can
423
- use <code>errors[:attribute]</code>. It returns an array of all the errors for
424
- <code>:attribute</code>. If there are no errors on the specified attribute, an empty array
425
- is returned.</p><p>This method is only useful <em>after</em> validations have been run, because it only
426
- inspects the errors collection and does not trigger validations itself. It's
427
- different from the <code>ActiveRecord::Base#invalid?</code> method explained above because
428
- it doesn't verify the validity of the object as a whole. It only checks to see
429
- whether there are errors found on an individual attribute of the object.</p><div class="code_container">
430
- <pre class="brush: ruby; gutter: false; toolbar: false">
431
- class Person &lt; ActiveRecord::Base
432
- validates :name, presence: true
433
- end
434
-
435
- &gt;&gt; Person.new.errors[:name].any? # =&gt; false
436
- &gt;&gt; Person.create.errors[:name].any? # =&gt; true
437
-
438
- </pre>
439
- </div>
440
- <p>We'll cover validation errors in greater depth in the <a href="#working-with-validation-errors">Working with Validation
441
- Errors</a> section. For now, let's turn to the
442
- built-in validation helpers that Rails provides by default.</p><h3 id="validation-helpers">2 Validation Helpers</h3><p>Active Record offers many pre-defined validation helpers that you can use
443
- directly inside your class definitions. These helpers provide common validation
444
- rules. Every time a validation fails, an error message is added to the object's
445
- <code>errors</code> collection, and this message is associated with the attribute being
446
- validated.</p><p>Each helper accepts an arbitrary number of attribute names, so with a single
447
- line of code you can add the same kind of validation to several attributes.</p><p>All of them accept the <code>:on</code> and <code>:message</code> options, which define when the
448
- validation should be run and what message should be added to the <code>errors</code>
449
- collection if it fails, respectively. The <code>:on</code> option takes one of the values
450
- <code>:create</code> or <code>:update</code>. There is a default error
451
- message for each one of the validation helpers. These messages are used when
452
- the <code>:message</code> option isn't specified. Let's take a look at each one of the
453
- available helpers.</p><h4 id="acceptance">2.1 <code>acceptance</code>
454
- </h4><p>This method validates that a checkbox on the user interface was checked when a
455
- form was submitted. This is typically used when the user needs to agree to your
456
- application's terms of service, confirm reading some text, or any similar
457
- concept. This validation is very specific to web applications and this
458
- 'acceptance' does not need to be recorded anywhere in your database (if you
459
- don't have a field for it, the helper will just create a virtual attribute).</p><div class="code_container">
460
- <pre class="brush: ruby; gutter: false; toolbar: false">
461
- class Person &lt; ActiveRecord::Base
462
- validates :terms_of_service, acceptance: true
463
- end
464
-
465
- </pre>
466
- </div>
467
- <p>The default error message for this helper is <em>"must be accepted"</em>.</p><p>It can receive an <code>:accept</code> option, which determines the value that will be
468
- considered acceptance. It defaults to "1" and can be easily changed.</p><div class="code_container">
469
- <pre class="brush: ruby; gutter: false; toolbar: false">
470
- class Person &lt; ActiveRecord::Base
471
- validates :terms_of_service, acceptance: { accept: 'yes' }
472
- end
473
-
474
- </pre>
475
- </div>
476
- <h4 id="validates_associated">2.2 <code>validates_associated</code>
477
- </h4><p>You should use this helper when your model has associations with other models
478
- and they also need to be validated. When you try to save your object, <code>valid?</code>
479
- will be called upon each one of the associated objects.</p><div class="code_container">
480
- <pre class="brush: ruby; gutter: false; toolbar: false">
481
- class Library &lt; ActiveRecord::Base
482
- has_many :books
483
- validates_associated :books
484
- end
485
-
486
- </pre>
487
- </div>
488
- <p>This validation will work with all of the association types.</p><div class="warning"><p>Don't use <code>validates_associated</code> on both ends of your associations.
489
- They would call each other in an infinite loop.</p></div><p>The default error message for <code>validates_associated</code> is <em>"is invalid"</em>. Note
490
- that each associated object will contain its own <code>errors</code> collection; errors do
491
- not bubble up to the calling model.</p><h4 id="confirmation">2.3 <code>confirmation</code>
492
- </h4><p>You should use this helper when you have two text fields that should receive
493
- exactly the same content. For example, you may want to confirm an email address
494
- or a password. This validation creates a virtual attribute whose name is the
495
- name of the field that has to be confirmed with "_confirmation" appended.</p><div class="code_container">
496
- <pre class="brush: ruby; gutter: false; toolbar: false">
497
- class Person &lt; ActiveRecord::Base
498
- validates :email, confirmation: true
499
- end
500
-
501
- </pre>
502
- </div>
503
- <p>In your view template you could use something like</p><div class="code_container">
504
- <pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
505
- &lt;%= text_field :person, :email %&gt;
506
- &lt;%= text_field :person, :email_confirmation %&gt;
507
-
508
- </pre>
509
- </div>
510
- <p>This check is performed only if <code>email_confirmation</code> is not <code>nil</code>. To require
511
- confirmation, make sure to add a presence check for the confirmation attribute
512
- (we'll take a look at <code>presence</code> later on this guide):</p><div class="code_container">
513
- <pre class="brush: ruby; gutter: false; toolbar: false">
514
- class Person &lt; ActiveRecord::Base
515
- validates :email, confirmation: true
516
- validates :email_confirmation, presence: true
517
- end
518
-
519
- </pre>
520
- </div>
521
- <p>The default error message for this helper is <em>"doesn't match confirmation"</em>.</p><h4 id="exclusion">2.4 <code>exclusion</code>
522
- </h4><p>This helper validates that the attributes' values are not included in a given
523
- set. In fact, this set can be any enumerable object.</p><div class="code_container">
524
- <pre class="brush: ruby; gutter: false; toolbar: false">
525
- class Account &lt; ActiveRecord::Base
526
- validates :subdomain, exclusion: { in: %w(www us ca jp),
527
- message: "%{value} is reserved." }
528
- end
529
-
530
- </pre>
531
- </div>
532
- <p>The <code>exclusion</code> helper has an option <code>:in</code> that receives the set of values that
533
- will not be accepted for the validated attributes. The <code>:in</code> option has an
534
- alias called <code>:within</code> that you can use for the same purpose, if you'd like to.
535
- This example uses the <code>:message</code> option to show how you can include the
536
- attribute's value.</p><p>The default error message is <em>"is reserved"</em>.</p><h4 id="format">2.5 <code>format</code>
537
- </h4><p>This helper validates the attributes' values by testing whether they match a
538
- given regular expression, which is specified using the <code>:with</code> option.</p><div class="code_container">
539
- <pre class="brush: ruby; gutter: false; toolbar: false">
540
- class Product &lt; ActiveRecord::Base
541
- validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
542
- message: "only allows letters" }
543
- end
544
-
545
- </pre>
546
- </div>
547
- <p>The default error message is <em>"is invalid"</em>.</p><h4 id="inclusion">2.6 <code>inclusion</code>
548
- </h4><p>This helper validates that the attributes' values are included in a given set.
549
- In fact, this set can be any enumerable object.</p><div class="code_container">
550
- <pre class="brush: ruby; gutter: false; toolbar: false">
551
- class Coffee &lt; ActiveRecord::Base
552
- validates :size, inclusion: { in: %w(small medium large),
553
- message: "%{value} is not a valid size" }
554
- end
555
-
556
- </pre>
557
- </div>
558
- <p>The <code>inclusion</code> helper has an option <code>:in</code> that receives the set of values that
559
- will be accepted. The <code>:in</code> option has an alias called <code>:within</code> that you can
560
- use for the same purpose, if you'd like to. The previous example uses the
561
- <code>:message</code> option to show how you can include the attribute's value.</p><p>The default error message for this helper is <em>"is not included in the list"</em>.</p><h4 id="length">2.7 <code>length</code>
562
- </h4><p>This helper validates the length of the attributes' values. It provides a
563
- variety of options, so you can specify length constraints in different ways:</p><div class="code_container">
564
- <pre class="brush: ruby; gutter: false; toolbar: false">
565
- class Person &lt; ActiveRecord::Base
566
- validates :name, length: { minimum: 2 }
567
- validates :bio, length: { maximum: 500 }
568
- validates :password, length: { in: 6..20 }
569
- validates :registration_number, length: { is: 6 }
570
- end
571
-
572
- </pre>
573
- </div>
574
- <p>The possible length constraint options are:</p>
575
- <ul>
576
- <li>
577
- <code>:minimum</code> - The attribute cannot have less than the specified length.</li>
578
- <li>
579
- <code>:maximum</code> - The attribute cannot have more than the specified length.</li>
580
- <li>
581
- <code>:in</code> (or <code>:within</code>) - The attribute length must be included in a given
582
- interval. The value for this option must be a range.</li>
583
- <li>
584
- <code>:is</code> - The attribute length must be equal to the given value.</li>
585
- </ul>
586
- <p>The default error messages depend on the type of length validation being
587
- performed. You can personalize these messages using the <code>:wrong_length</code>,
588
- <code>:too_long</code>, and <code>:too_short</code> options and <code>%{count}</code> as a placeholder for the
589
- number corresponding to the length constraint being used. You can still use the
590
- <code>:message</code> option to specify an error message.</p><div class="code_container">
591
- <pre class="brush: ruby; gutter: false; toolbar: false">
592
- class Person &lt; ActiveRecord::Base
593
- validates :bio, length: { maximum: 1000,
594
- too_long: "%{count} characters is the maximum allowed" }
595
- end
596
-
597
- </pre>
598
- </div>
599
- <p>This helper counts characters by default, but you can split the value in a
600
- different way using the <code>:tokenizer</code> option:</p><div class="code_container">
601
- <pre class="brush: ruby; gutter: false; toolbar: false">
602
- class Essay &lt; ActiveRecord::Base
603
- validates :content, length: {
604
- minimum: 300,
605
- maximum: 400,
606
- tokenizer: lambda { |str| str.scan(/\w+/) },
607
- too_short: "must have at least %{count} words",
608
- too_long: "must have at most %{count} words"
609
- }
610
- end
611
-
612
- </pre>
613
- </div>
614
- <p>Note that the default error messages are plural (e.g., "is too short (minimum
615
- is %{count} characters)"). For this reason, when <code>:minimum</code> is 1 you should
616
- provide a personalized message or use <code>presence: true</code> instead. When
617
- <code>:in</code> or <code>:within</code> have a lower limit of 1, you should either provide a
618
- personalized message or call <code>presence</code> prior to <code>length</code>.</p><h4 id="numericality">2.8 <code>numericality</code>
619
- </h4><p>This helper validates that your attributes have only numeric values. By
620
- default, it will match an optional sign followed by an integral or floating
621
- point number. To specify that only integral numbers are allowed set
622
- <code>:only_integer</code> to true.</p><p>If you set <code>:only_integer</code> to <code>true</code>, then it will use the</p><div class="code_container">
623
- <pre class="brush: ruby; gutter: false; toolbar: false">
624
- /\A[+-]?\d+\Z/
625
-
626
- </pre>
627
- </div>
628
- <p>regular expression to validate the attribute's value. Otherwise, it will try to
629
- convert the value to a number using <code>Float</code>.</p><div class="warning"><p>Note that the regular expression above allows a trailing newline
630
- character.</p></div><div class="code_container">
631
- <pre class="brush: ruby; gutter: false; toolbar: false">
632
- class Player &lt; ActiveRecord::Base
633
- validates :points, numericality: true
634
- validates :games_played, numericality: { only_integer: true }
635
- end
636
-
637
- </pre>
638
- </div>
639
- <p>Besides <code>:only_integer</code>, this helper also accepts the following options to add
640
- constraints to acceptable values:</p>
641
- <ul>
642
- <li>
643
- <code>:greater_than</code> - Specifies the value must be greater than the supplied
644
- value. The default error message for this option is <em>"must be greater than
645
- %{count}"</em>.</li>
646
- <li>
647
- <code>:greater_than_or_equal_to</code> - Specifies the value must be greater than or
648
- equal to the supplied value. The default error message for this option is
649
- <em>"must be greater than or equal to %{count}"</em>.</li>
650
- <li>
651
- <code>:equal_to</code> - Specifies the value must be equal to the supplied value. The
652
- default error message for this option is <em>"must be equal to %{count}"</em>.</li>
653
- <li>
654
- <code>:less_than</code> - Specifies the value must be less than the supplied value. The
655
- default error message for this option is <em>"must be less than %{count}"</em>.</li>
656
- <li>
657
- <code>:less_than_or_equal_to</code> - Specifies the value must be less than or equal the
658
- supplied value. The default error message for this option is <em>"must be less
659
- than or equal to %{count}"</em>.</li>
660
- <li>
661
- <code>:odd</code> - Specifies the value must be an odd number if set to true. The
662
- default error message for this option is <em>"must be odd"</em>.</li>
663
- <li>
664
- <code>:even</code> - Specifies the value must be an even number if set to true. The
665
- default error message for this option is <em>"must be even"</em>.</li>
666
- </ul>
667
- <p>The default error message is <em>"is not a number"</em>.</p><h4 id="presence">2.9 <code>presence</code>
668
- </h4><p>This helper validates that the specified attributes are not empty. It uses the
669
- <code>blank?</code> method to check if the value is either <code>nil</code> or a blank string, that
670
- is, a string that is either empty or consists of whitespace.</p><div class="code_container">
671
- <pre class="brush: ruby; gutter: false; toolbar: false">
672
- class Person &lt; ActiveRecord::Base
673
- validates :name, :login, :email, presence: true
674
- end
675
-
676
- </pre>
677
- </div>
678
- <p>If you want to be sure that an association is present, you'll need to test
679
- whether the associated object itself is present, and not the foreign key used
680
- to map the association.</p><div class="code_container">
681
- <pre class="brush: ruby; gutter: false; toolbar: false">
682
- class LineItem &lt; ActiveRecord::Base
683
- belongs_to :order
684
- validates :order, presence: true
685
- end
686
-
687
- </pre>
688
- </div>
689
- <p>In order to validate associated records whose presence is required, you must
690
- specify the <code>:inverse_of</code> option for the association:</p><div class="code_container">
691
- <pre class="brush: ruby; gutter: false; toolbar: false">
692
- class Order &lt; ActiveRecord::Base
693
- has_many :line_items, inverse_of: :order
694
- end
695
-
696
- </pre>
697
- </div>
698
- <p>If you validate the presence of an object associated via a <code>has_one</code> or
699
- <code>has_many</code> relationship, it will check that the object is neither <code>blank?</code> nor
700
- <code>marked_for_destruction?</code>.</p><p>Since <code>false.blank?</code> is true, if you want to validate the presence of a boolean
701
- field you should use <code>validates :field_name, inclusion: { in: [true, false] }</code>.</p><p>The default error message is <em>"can't be blank"</em>.</p><h4 id="absence">2.10 <code>absence</code>
702
- </h4><p>This helper validates that the specified attributes are absent. It uses the
703
- <code>present?</code> method to check if the value is not either nil or a blank string, that
704
- is, a string that is either empty or consists of whitespace.</p><div class="code_container">
705
- <pre class="brush: ruby; gutter: false; toolbar: false">
706
- class Person &lt; ActiveRecord::Base
707
- validates :name, :login, :email, absence: true
708
- end
709
-
710
- </pre>
711
- </div>
712
- <p>If you want to be sure that an association is absent, you'll need to test
713
- whether the associated object itself is absent, and not the foreign key used
714
- to map the association.</p><div class="code_container">
715
- <pre class="brush: ruby; gutter: false; toolbar: false">
716
- class LineItem &lt; ActiveRecord::Base
717
- belongs_to :order
718
- validates :order, absence: true
719
- end
720
-
721
- </pre>
722
- </div>
723
- <p>In order to validate associated records whose absence is required, you must
724
- specify the <code>:inverse_of</code> option for the association:</p><div class="code_container">
725
- <pre class="brush: ruby; gutter: false; toolbar: false">
726
- class Order &lt; ActiveRecord::Base
727
- has_many :line_items, inverse_of: :order
728
- end
729
-
730
- </pre>
731
- </div>
732
- <p>If you validate the absence of an object associated via a <code>has_one</code> or
733
- <code>has_many</code> relationship, it will check that the object is neither <code>present?</code> nor
734
- <code>marked_for_destruction?</code>.</p><p>Since <code>false.present?</code> is false, if you want to validate the absence of a boolean
735
- field you should use <code>validates :field_name, exclusion: { in: [true, false] }</code>.</p><p>The default error message is <em>"must be blank"</em>.</p><h4 id="uniqueness">2.11 <code>uniqueness</code>
736
- </h4><p>This helper validates that the attribute's value is unique right before the
737
- object gets saved. It does not create a uniqueness constraint in the database,
738
- so it may happen that two different database connections create two records
739
- with the same value for a column that you intend to be unique. To avoid that,
740
- you must create a unique index on both columns in your database. See
741
- <a href="http://dev.mysql.com/doc/refman/5.6/en/multiple-column-indexes.html">the MySQL manual</a>
742
- for more details about multiple column indexes.</p><div class="code_container">
743
- <pre class="brush: ruby; gutter: false; toolbar: false">
744
- class Account &lt; ActiveRecord::Base
745
- validates :email, uniqueness: true
746
- end
747
-
748
- </pre>
749
- </div>
750
- <p>The validation happens by performing an SQL query into the model's table,
751
- searching for an existing record with the same value in that attribute.</p><p>There is a <code>:scope</code> option that you can use to specify other attributes that
752
- are used to limit the uniqueness check:</p><div class="code_container">
753
- <pre class="brush: ruby; gutter: false; toolbar: false">
754
- class Holiday &lt; ActiveRecord::Base
755
- validates :name, uniqueness: { scope: :year,
756
- message: "should happen once per year" }
757
- end
758
-
759
- </pre>
760
- </div>
761
- <p>There is also a <code>:case_sensitive</code> option that you can use to define whether the
762
- uniqueness constraint will be case sensitive or not. This option defaults to
763
- true.</p><div class="code_container">
764
- <pre class="brush: ruby; gutter: false; toolbar: false">
765
- class Person &lt; ActiveRecord::Base
766
- validates :name, uniqueness: { case_sensitive: false }
767
- end
768
-
769
- </pre>
770
- </div>
771
- <div class="warning"><p>Note that some databases are configured to perform case-insensitive
772
- searches anyway.</p></div><p>The default error message is <em>"has already been taken"</em>.</p><h4 id="validates_with">2.12 <code>validates_with</code>
773
- </h4><p>This helper passes the record to a separate class for validation.</p><div class="code_container">
774
- <pre class="brush: ruby; gutter: false; toolbar: false">
775
- class GoodnessValidator &lt; ActiveModel::Validator
776
- def validate(record)
777
- if record.first_name == "Evil"
778
- record.errors[:base] &lt;&lt; "This person is evil"
779
- end
780
- end
781
- end
782
-
783
- class Person &lt; ActiveRecord::Base
784
- validates_with GoodnessValidator
785
- end
786
-
787
- </pre>
788
- </div>
789
- <div class="note"><p>Errors added to <code>record.errors[:base]</code> relate to the state of the record
790
- as a whole, and not to a specific attribute.</p></div><p>The <code>validates_with</code> helper takes a class, or a list of classes to use for
791
- validation. There is no default error message for <code>validates_with</code>. You must
792
- manually add errors to the record's errors collection in the validator class.</p><p>To implement the validate method, you must have a <code>record</code> parameter defined,
793
- which is the record to be validated.</p><p>Like all other validations, <code>validates_with</code> takes the <code>:if</code>, <code>:unless</code> and
794
- <code>:on</code> options. If you pass any other options, it will send those options to the
795
- validator class as <code>options</code>:</p><div class="code_container">
796
- <pre class="brush: ruby; gutter: false; toolbar: false">
797
- class GoodnessValidator &lt; ActiveModel::Validator
798
- def validate(record)
799
- if options[:fields].any?{|field| record.send(field) == "Evil" }
800
- record.errors[:base] &lt;&lt; "This person is evil"
801
- end
802
- end
803
- end
804
-
805
- class Person &lt; ActiveRecord::Base
806
- validates_with GoodnessValidator, fields: [:first_name, :last_name]
807
- end
808
-
809
- </pre>
810
- </div>
811
- <p>Note that the validator will be initialized <em>only once</em> for the whole application
812
- life cycle, and not on each validation run, so be careful about using instance
813
- variables inside it.</p><p>If your validator is complex enough that you want instance variables, you can
814
- easily use a plain old Ruby object instead:</p><div class="code_container">
815
- <pre class="brush: ruby; gutter: false; toolbar: false">
816
- class Person &lt; ActiveRecord::Base
817
- validate do |person|
818
- GoodnessValidator.new(person).validate
819
- end
820
- end
821
-
822
- class GoodnessValidator
823
- def initialize(person)
824
- @person = person
825
- end
826
-
827
- def validate
828
- if some_complex_condition_involving_ivars_and_private_methods?
829
- @person.errors[:base] &lt;&lt; "This person is evil"
830
- end
831
- end
832
-
833
- # ...
834
- end
835
-
836
- </pre>
837
- </div>
838
- <h4 id="validates_each">2.13 <code>validates_each</code>
839
- </h4><p>This helper validates attributes against a block. It doesn't have a predefined
840
- validation function. You should create one using a block, and every attribute
841
- passed to <code>validates_each</code> will be tested against it. In the following example,
842
- we don't want names and surnames to begin with lower case.</p><div class="code_container">
843
- <pre class="brush: ruby; gutter: false; toolbar: false">
844
- class Person &lt; ActiveRecord::Base
845
- validates_each :name, :surname do |record, attr, value|
846
- record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
847
- end
848
- end
849
-
850
- </pre>
851
- </div>
852
- <p>The block receives the record, the attribute's name and the attribute's value.
853
- You can do anything you like to check for valid data within the block. If your
854
- validation fails, you should add an error message to the model, therefore
855
- making it invalid.</p><h3 id="common-validation-options">3 Common Validation Options</h3><p>These are common validation options:</p><h4 id=":allow_nil">3.1 <code>:allow_nil</code>
856
- </h4><p>The <code>:allow_nil</code> option skips the validation when the value being validated is
857
- <code>nil</code>.</p><div class="code_container">
858
- <pre class="brush: ruby; gutter: false; toolbar: false">
859
- class Coffee &lt; ActiveRecord::Base
860
- validates :size, inclusion: { in: %w(small medium large),
861
- message: "%{value} is not a valid size" }, allow_nil: true
862
- end
863
-
864
- </pre>
865
- </div>
866
- <h4 id=":allow_blank">3.2 <code>:allow_blank</code>
867
- </h4><p>The <code>:allow_blank</code> option is similar to the <code>:allow_nil</code> option. This option
868
- will let validation pass if the attribute's value is <code>blank?</code>, like <code>nil</code> or an
869
- empty string for example.</p><div class="code_container">
870
- <pre class="brush: ruby; gutter: false; toolbar: false">
871
- class Topic &lt; ActiveRecord::Base
872
- validates :title, length: { is: 5 }, allow_blank: true
873
- end
874
-
875
- Topic.create(title: "").valid? # =&gt; true
876
- Topic.create(title: nil).valid? # =&gt; true
877
-
878
- </pre>
879
- </div>
880
- <h4 id=":message">3.3 <code>:message</code>
881
- </h4><p>As you've already seen, the <code>:message</code> option lets you specify the message that
882
- will be added to the <code>errors</code> collection when validation fails. When this
883
- option is not used, Active Record will use the respective default error message
884
- for each validation helper.</p><h4 id=":on">3.4 <code>:on</code>
885
- </h4><p>The <code>:on</code> option lets you specify when the validation should happen. The
886
- default behavior for all the built-in validation helpers is to be run on save
887
- (both when you're creating a new record and when you're updating it). If you
888
- want to change it, you can use <code>on: :create</code> to run the validation only when a
889
- new record is created or <code>on: :update</code> to run the validation only when a record
890
- is updated.</p><div class="code_container">
891
- <pre class="brush: ruby; gutter: false; toolbar: false">
892
- class Person &lt; ActiveRecord::Base
893
- # it will be possible to update email with a duplicated value
894
- validates :email, uniqueness: true, on: :create
895
-
896
- # it will be possible to create the record with a non-numerical age
897
- validates :age, numericality: true, on: :update
898
-
899
- # the default (validates on both create and update)
900
- validates :name, presence: true
901
- end
902
-
903
- </pre>
904
- </div>
905
- <h3 id="strict-validations">4 Strict Validations</h3><p>You can also specify validations to be strict and raise
906
- <code>ActiveModel::StrictValidationFailed</code> when the object is invalid.</p><div class="code_container">
907
- <pre class="brush: ruby; gutter: false; toolbar: false">
908
- class Person &lt; ActiveRecord::Base
909
- validates :name, presence: { strict: true }
910
- end
911
-
912
- Person.new.valid? # =&gt; ActiveModel::StrictValidationFailed: Name can't be blank
913
-
914
- </pre>
915
- </div>
916
- <p>There is also an ability to pass custom exception to <code>:strict</code> option.</p><div class="code_container">
917
- <pre class="brush: ruby; gutter: false; toolbar: false">
918
- class Person &lt; ActiveRecord::Base
919
- validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
920
- end
921
-
922
- Person.new.valid? # =&gt; TokenGenerationException: Token can't be blank
923
-
924
- </pre>
925
- </div>
926
- <h3 id="conditional-validation">5 Conditional Validation</h3><p>Sometimes it will make sense to validate an object only when a given predicate
927
- is satisfied. You can do that by using the <code>:if</code> and <code>:unless</code> options, which
928
- can take a symbol, a string, a <code>Proc</code> or an <code>Array</code>. You may use the <code>:if</code>
929
- option when you want to specify when the validation <strong>should</strong> happen. If you
930
- want to specify when the validation <strong>should not</strong> happen, then you may use the
931
- <code>:unless</code> option.</p><h4 id="using-a-symbol-with-:if-and-:unless">5.1 Using a Symbol with <code>:if</code> and <code>:unless</code>
932
- </h4><p>You can associate the <code>:if</code> and <code>:unless</code> options with a symbol corresponding
933
- to the name of a method that will get called right before validation happens.
934
- This is the most commonly used option.</p><div class="code_container">
935
- <pre class="brush: ruby; gutter: false; toolbar: false">
936
- class Order &lt; ActiveRecord::Base
937
- validates :card_number, presence: true, if: :paid_with_card?
938
-
939
- def paid_with_card?
940
- payment_type == "card"
941
- end
942
- end
943
-
944
- </pre>
945
- </div>
946
- <h4 id="using-a-string-with-:if-and-:unless">5.2 Using a String with <code>:if</code> and <code>:unless</code>
947
- </h4><p>You can also use a string that will be evaluated using <code>eval</code> and needs to
948
- contain valid Ruby code. You should use this option only when the string
949
- represents a really short condition.</p><div class="code_container">
950
- <pre class="brush: ruby; gutter: false; toolbar: false">
951
- class Person &lt; ActiveRecord::Base
952
- validates :surname, presence: true, if: "name.nil?"
953
- end
954
-
955
- </pre>
956
- </div>
957
- <h4 id="using-a-proc-with-:if-and-:unless">5.3 Using a Proc with <code>:if</code> and <code>:unless</code>
958
- </h4><p>Finally, it's possible to associate <code>:if</code> and <code>:unless</code> with a <code>Proc</code> object
959
- which will be called. Using a <code>Proc</code> object gives you the ability to write an
960
- inline condition instead of a separate method. This option is best suited for
961
- one-liners.</p><div class="code_container">
962
- <pre class="brush: ruby; gutter: false; toolbar: false">
963
- class Account &lt; ActiveRecord::Base
964
- validates :password, confirmation: true,
965
- unless: Proc.new { |a| a.password.blank? }
966
- end
967
-
968
- </pre>
969
- </div>
970
- <h4 id="grouping-conditional-validations">5.4 Grouping Conditional validations</h4><p>Sometimes it is useful to have multiple validations use one condition, it can
971
- be easily achieved using <code>with_options</code>.</p><div class="code_container">
972
- <pre class="brush: ruby; gutter: false; toolbar: false">
973
- class User &lt; ActiveRecord::Base
974
- with_options if: :is_admin? do |admin|
975
- admin.validates :password, length: { minimum: 10 }
976
- admin.validates :email, presence: true
977
- end
978
- end
979
-
980
- </pre>
981
- </div>
982
- <p>All validations inside of <code>with_options</code> block will have automatically passed
983
- the condition <code>if: :is_admin?</code></p><h4 id="combining-validation-conditions">5.5 Combining Validation Conditions</h4><p>On the other hand, when multiple conditions define whether or not a validation
984
- should happen, an <code>Array</code> can be used. Moreover, you can apply both <code>:if</code> and
985
- <code>:unless</code> to the same validation.</p><div class="code_container">
986
- <pre class="brush: ruby; gutter: false; toolbar: false">
987
- class Computer &lt; ActiveRecord::Base
988
- validates :mouse, presence: true,
989
- if: ["market.retail?", :desktop?],
990
- unless: Proc.new { |c| c.trackpad.present? }
991
- end
992
-
993
- </pre>
994
- </div>
995
- <p>The validation only runs when all the <code>:if</code> conditions and none of the
996
- <code>:unless</code> conditions are evaluated to <code>true</code>.</p><h3 id="performing-custom-validations">6 Performing Custom Validations</h3><p>When the built-in validation helpers are not enough for your needs, you can
997
- write your own validators or validation methods as you prefer.</p><h4 id="custom-validators">6.1 Custom Validators</h4><p>Custom validators are classes that extend <code>ActiveModel::Validator</code>. These
998
- classes must implement a <code>validate</code> method which takes a record as an argument
999
- and performs the validation on it. The custom validator is called using the
1000
- <code>validates_with</code> method.</p><div class="code_container">
1001
- <pre class="brush: ruby; gutter: false; toolbar: false">
1002
- class MyValidator &lt; ActiveModel::Validator
1003
- def validate(record)
1004
- unless record.name.starts_with? 'X'
1005
- record.errors[:name] &lt;&lt; 'Need a name starting with X please!'
1006
- end
1007
- end
1008
- end
1009
-
1010
- class Person
1011
- include ActiveModel::Validations
1012
- validates_with MyValidator
1013
- end
1014
-
1015
- </pre>
1016
- </div>
1017
- <p>The easiest way to add custom validators for validating individual attributes
1018
- is with the convenient <code>ActiveModel::EachValidator</code>. In this case, the custom
1019
- validator class must implement a <code>validate_each</code> method which takes three
1020
- arguments: record, attribute, and value. These correspond to the instance, the
1021
- attribute to be validated, and the value of the attribute in the passed
1022
- instance.</p><div class="code_container">
1023
- <pre class="brush: ruby; gutter: false; toolbar: false">
1024
- class EmailValidator &lt; ActiveModel::EachValidator
1025
- def validate_each(record, attribute, value)
1026
- unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
1027
- record.errors[attribute] &lt;&lt; (options[:message] || "is not an email")
1028
- end
1029
- end
1030
- end
1031
-
1032
- class Person &lt; ActiveRecord::Base
1033
- validates :email, presence: true, email: true
1034
- end
1035
-
1036
- </pre>
1037
- </div>
1038
- <p>As shown in the example, you can also combine standard validations with your
1039
- own custom validators.</p><h4 id="custom-methods">6.2 Custom Methods</h4><p>You can also create methods that verify the state of your models and add
1040
- messages to the <code>errors</code> collection when they are invalid. You must then
1041
- register these methods by using the <code>validate</code> class method, passing in the
1042
- symbols for the validation methods' names.</p><p>You can pass more than one symbol for each class method and the respective
1043
- validations will be run in the same order as they were registered.</p><div class="code_container">
1044
- <pre class="brush: ruby; gutter: false; toolbar: false">
1045
- class Invoice &lt; ActiveRecord::Base
1046
- validate :expiration_date_cannot_be_in_the_past,
1047
- :discount_cannot_be_greater_than_total_value
1048
-
1049
- def expiration_date_cannot_be_in_the_past
1050
- if expiration_date.present? &amp;&amp; expiration_date &lt; Date.today
1051
- errors.add(:expiration_date, "can't be in the past")
1052
- end
1053
- end
1054
-
1055
- def discount_cannot_be_greater_than_total_value
1056
- if discount &gt; total_value
1057
- errors.add(:discount, "can't be greater than total value")
1058
- end
1059
- end
1060
- end
1061
-
1062
- </pre>
1063
- </div>
1064
- <p>By default such validations will run every time you call <code>valid?</code>. It is also
1065
- possible to control when to run these custom validations by giving an <code>:on</code>
1066
- option to the <code>validate</code> method, with either: <code>:create</code> or <code>:update</code>.</p><div class="code_container">
1067
- <pre class="brush: ruby; gutter: false; toolbar: false">
1068
- class Invoice &lt; ActiveRecord::Base
1069
- validate :active_customer, on: :create
1070
-
1071
- def active_customer
1072
- errors.add(:customer_id, "is not active") unless customer.active?
1073
- end
1074
- end
1075
-
1076
- </pre>
1077
- </div>
1078
- <h3 id="working-with-validation-errors">7 Working with Validation Errors</h3><p>In addition to the <code>valid?</code> and <code>invalid?</code> methods covered earlier, Rails provides a number of methods for working with the <code>errors</code> collection and inquiring about the validity of objects.</p><p>The following is a list of the most commonly used methods. Please refer to the <code>ActiveModel::Errors</code> documentation for a list of all the available methods.</p><h4 id="errors">7.1 <code>errors</code>
1079
- </h4><p>Returns an instance of the class <code>ActiveModel::Errors</code> containing all errors. Each key is the attribute name and the value is an array of strings with all errors.</p><div class="code_container">
1080
- <pre class="brush: ruby; gutter: false; toolbar: false">
1081
- class Person &lt; ActiveRecord::Base
1082
- validates :name, presence: true, length: { minimum: 3 }
1083
- end
1084
-
1085
- person = Person.new
1086
- person.valid? # =&gt; false
1087
- person.errors.messages
1088
- # =&gt; {:name=&gt;["can't be blank", "is too short (minimum is 3 characters)"]}
1089
-
1090
- person = Person.new(name: "John Doe")
1091
- person.valid? # =&gt; true
1092
- person.errors.messages # =&gt; {}
1093
-
1094
- </pre>
1095
- </div>
1096
- <h4 id="working-with-validation-errors-errors[]">7.2 <code>errors[]</code>
1097
- </h4><p><code>errors[]</code> 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><div class="code_container">
1098
- <pre class="brush: ruby; gutter: false; toolbar: false">
1099
- class Person &lt; ActiveRecord::Base
1100
- validates :name, presence: true, length: { minimum: 3 }
1101
- end
1102
-
1103
- person = Person.new(name: "John Doe")
1104
- person.valid? # =&gt; true
1105
- person.errors[:name] # =&gt; []
1106
-
1107
- person = Person.new(name: "JD")
1108
- person.valid? # =&gt; false
1109
- person.errors[:name] # =&gt; ["is too short (minimum is 3 characters)"]
1110
-
1111
- person = Person.new
1112
- person.valid? # =&gt; false
1113
- person.errors[:name]
1114
- # =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]
1115
-
1116
- </pre>
1117
- </div>
1118
- <h4 id="errors.add">7.3 <code>errors.add</code>
1119
- </h4><p>The <code>add</code> method lets you manually add messages that are related to particular attributes. You can use the <code>errors.full_messages</code> or <code>errors.to_a</code> 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). <code>add</code> receives the name of the attribute you want to add the message to, and the message itself.</p><div class="code_container">
1120
- <pre class="brush: ruby; gutter: false; toolbar: false">
1121
- class Person &lt; ActiveRecord::Base
1122
- def a_method_used_for_validation_purposes
1123
- errors.add(:name, "cannot contain the characters !@#%*()_-+=")
1124
- end
1125
- end
1126
-
1127
- person = Person.create(name: "!@#")
1128
-
1129
- person.errors[:name]
1130
- # =&gt; ["cannot contain the characters !@#%*()_-+="]
1131
-
1132
- person.errors.full_messages
1133
- # =&gt; ["Name cannot contain the characters !@#%*()_-+="]
1134
-
1135
- </pre>
1136
- </div>
1137
- <p>Another way to do this is using <code>[]=</code> setter</p><div class="code_container">
1138
- <pre class="brush: ruby; gutter: false; toolbar: false">
1139
- class Person &lt; ActiveRecord::Base
1140
- def a_method_used_for_validation_purposes
1141
- errors[:name] = "cannot contain the characters !@#%*()_-+="
1142
- end
1143
- end
1144
-
1145
- person = Person.create(name: "!@#")
1146
-
1147
- person.errors[:name]
1148
- # =&gt; ["cannot contain the characters !@#%*()_-+="]
1149
-
1150
- person.errors.to_a
1151
- # =&gt; ["Name cannot contain the characters !@#%*()_-+="]
1152
-
1153
- </pre>
1154
- </div>
1155
- <h4 id="errors[:base]">7.4 <code>errors[:base]</code>
1156
- </h4><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 <code>errors[:base]</code> is an array, you can simply add a string to it and it will be used as an error message.</p><div class="code_container">
1157
- <pre class="brush: ruby; gutter: false; toolbar: false">
1158
- class Person &lt; ActiveRecord::Base
1159
- def a_method_used_for_validation_purposes
1160
- errors[:base] &lt;&lt; "This person is invalid because ..."
1161
- end
1162
- end
1163
-
1164
- </pre>
1165
- </div>
1166
- <h4 id="errors.clear">7.5 <code>errors.clear</code>
1167
- </h4><p>The <code>clear</code> method is used when you intentionally want to clear all the messages in the <code>errors</code> collection. Of course, calling <code>errors.clear</code> upon an invalid object won't actually make it valid: the <code>errors</code> collection will now be empty, but the next time you call <code>valid?</code> or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the <code>errors</code> collection will be filled again.</p><div class="code_container">
1168
- <pre class="brush: ruby; gutter: false; toolbar: false">
1169
- class Person &lt; ActiveRecord::Base
1170
- validates :name, presence: true, length: { minimum: 3 }
1171
- end
1172
-
1173
- person = Person.new
1174
- person.valid? # =&gt; false
1175
- person.errors[:name]
1176
- # =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]
1177
-
1178
- person.errors.clear
1179
- person.errors.empty? # =&gt; true
1180
-
1181
- p.save # =&gt; false
1182
-
1183
- p.errors[:name]
1184
- # =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]
1185
-
1186
- </pre>
1187
- </div>
1188
- <h4 id="errors.size">7.6 <code>errors.size</code>
1189
- </h4><p>The <code>size</code> method returns the total number of error messages for the object.</p><div class="code_container">
1190
- <pre class="brush: ruby; gutter: false; toolbar: false">
1191
- class Person &lt; ActiveRecord::Base
1192
- validates :name, presence: true, length: { minimum: 3 }
1193
- end
1194
-
1195
- person = Person.new
1196
- person.valid? # =&gt; false
1197
- person.errors.size # =&gt; 2
1198
-
1199
- person = Person.new(name: "Andrea", email: "andrea@example.com")
1200
- person.valid? # =&gt; true
1201
- person.errors.size # =&gt; 0
1202
-
1203
- </pre>
1204
- </div>
1205
- <h3 id="displaying-validation-errors-in-views">8 Displaying Validation Errors in Views</h3><p>Once you've created a model and added validations, if that model is created via
1206
- a web form, you probably want to display an error message when one of the
1207
- validations fail.</p><p>Because every application handles this kind of thing differently, Rails does
1208
- not include any view helpers to help you generate these messages directly.
1209
- However, due to the rich number of methods Rails gives you to interact with
1210
- validations in general, it's fairly easy to build your own. In addition, when
1211
- generating a scaffold, Rails will put some ERB into the <code>_form.html.erb</code> that
1212
- it generates that displays the full list of errors on that model.</p><p>Assuming we have a model that's been saved in an instance variable named
1213
- <code>@article</code>, it looks like this:</p><div class="code_container">
1214
- <pre class="brush: ruby; gutter: false; toolbar: false">
1215
- &lt;% if @article.errors.any? %&gt;
1216
- &lt;div id="error_explanation"&gt;
1217
- &lt;h2&gt;&lt;%= pluralize(@article.errors.count, "error") %&gt; prohibited this article from being saved:&lt;/h2&gt;
1218
-
1219
- &lt;ul&gt;
1220
- &lt;% @article.errors.full_messages.each do |msg| %&gt;
1221
- &lt;li&gt;&lt;%= msg %&gt;&lt;/li&gt;
1222
- &lt;% end %&gt;
1223
- &lt;/ul&gt;
1224
- &lt;/div&gt;
1225
- &lt;% end %&gt;
1226
-
1227
- </pre>
1228
- </div>
1229
- <p>Furthermore, if you use the Rails form helpers to generate your forms, when
1230
- a validation error occurs on a field, it will generate an extra <code>&lt;div&gt;</code> around
1231
- the entry.</p><div class="code_container">
1232
- <pre class="brush: plain; gutter: false; toolbar: false">
1233
- &lt;div class="field_with_errors"&gt;
1234
- &lt;input id="article_title" name="article[title]" size="30" type="text" value=""&gt;
1235
- &lt;/div&gt;
1236
-
1237
- </pre>
1238
- </div>
1239
- <p>You can then style this div however you'd like. The default scaffold that
1240
- Rails generates, for example, adds this CSS rule:</p><div class="code_container">
1241
- <pre class="brush: plain; gutter: false; toolbar: false">
1242
- .field_with_errors {
1243
- padding: 2px;
1244
- background-color: red;
1245
- display: table;
1246
- }
1247
-
1248
- </pre>
1249
- </div>
1250
- <p>This means that any field with an error ends up with a 2 pixel red border.</p>
1251
-
1252
- <h3>Feedback</h3>
1253
- <p>
1254
- You're encouraged to help improve the quality of this guide.
1255
- </p>
1256
- <p>
1257
- Please contribute if you see any typos or factual errors.
1258
- To get started, you can read our <a href="http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section.
1259
- </p>
1260
- <p>
1261
- You may also find incomplete content, or stuff that is not up to date.
1262
- Please do add any missing documentation for master. Make sure to check
1263
- <a href="http://edgeguides.rubyonrails.org">Edge Guides</a> first to verify
1264
- if the issues are already fixed or not on the master branch.
1265
- Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
1266
- for style and conventions.
1267
- </p>
1268
- <p>
1269
- If for whatever reason you spot something to fix but cannot patch it yourself, please
1270
- <a href="https://github.com/rails/rails/issues">open an issue</a>.
1271
- </p>
1272
- <p>And last but not least, any kind of discussion regarding Ruby on Rails
1273
- documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
1274
- </p>
1275
- </div>
1276
- </div>
1277
- </div>
1278
-
1279
- <hr class="hide" />
1280
- <div id="footer">
1281
- <div class="wrapper">
1282
- <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p>
1283
- <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
1284
-
1285
- </div>
1286
- </div>
1287
-
1288
- <script type="text/javascript" src="javascripts/jquery.min.js"></script>
1289
- <script type="text/javascript" src="javascripts/responsive-tables.js"></script>
1290
- <script type="text/javascript" src="javascripts/guides.js"></script>
1291
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
1292
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
1293
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
1294
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
1295
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
1296
- <script type="text/javascript">
1297
- SyntaxHighlighter.all();
1298
- $(guidesIndex.bind);
1299
- </script>
1300
- </body>
1301
- </html>