rails 3.2.22.5 → 4.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

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