rails 4.2.6.rc1 → 5.2.8.1

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 (218) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +24 -12
  3. metadata +54 -248
  4. data/guides/CHANGELOG.md +0 -73
  5. data/guides/Rakefile +0 -79
  6. data/guides/assets/images/akshaysurve.jpg +0 -0
  7. data/guides/assets/images/belongs_to.png +0 -0
  8. data/guides/assets/images/book_icon.gif +0 -0
  9. data/guides/assets/images/bullet.gif +0 -0
  10. data/guides/assets/images/chapters_icon.gif +0 -0
  11. data/guides/assets/images/check_bullet.gif +0 -0
  12. data/guides/assets/images/credits_pic_blank.gif +0 -0
  13. data/guides/assets/images/csrf.png +0 -0
  14. data/guides/assets/images/edge_badge.png +0 -0
  15. data/guides/assets/images/favicon.ico +0 -0
  16. data/guides/assets/images/feature_tile.gif +0 -0
  17. data/guides/assets/images/footer_tile.gif +0 -0
  18. data/guides/assets/images/fxn.png +0 -0
  19. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  20. data/guides/assets/images/getting_started/challenge.png +0 -0
  21. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  22. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  23. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  24. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  25. data/guides/assets/images/getting_started/new_article.png +0 -0
  26. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  28. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  29. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  30. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  32. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  33. data/guides/assets/images/grey_bullet.gif +0 -0
  34. data/guides/assets/images/habtm.png +0 -0
  35. data/guides/assets/images/has_many.png +0 -0
  36. data/guides/assets/images/has_many_through.png +0 -0
  37. data/guides/assets/images/has_one.png +0 -0
  38. data/guides/assets/images/has_one_through.png +0 -0
  39. data/guides/assets/images/header_backdrop.png +0 -0
  40. data/guides/assets/images/header_tile.gif +0 -0
  41. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  42. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  44. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  45. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  46. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  47. data/guides/assets/images/icons/README +0 -5
  48. data/guides/assets/images/icons/callouts/1.png +0 -0
  49. data/guides/assets/images/icons/callouts/10.png +0 -0
  50. data/guides/assets/images/icons/callouts/11.png +0 -0
  51. data/guides/assets/images/icons/callouts/12.png +0 -0
  52. data/guides/assets/images/icons/callouts/13.png +0 -0
  53. data/guides/assets/images/icons/callouts/14.png +0 -0
  54. data/guides/assets/images/icons/callouts/15.png +0 -0
  55. data/guides/assets/images/icons/callouts/2.png +0 -0
  56. data/guides/assets/images/icons/callouts/3.png +0 -0
  57. data/guides/assets/images/icons/callouts/4.png +0 -0
  58. data/guides/assets/images/icons/callouts/5.png +0 -0
  59. data/guides/assets/images/icons/callouts/6.png +0 -0
  60. data/guides/assets/images/icons/callouts/7.png +0 -0
  61. data/guides/assets/images/icons/callouts/8.png +0 -0
  62. data/guides/assets/images/icons/callouts/9.png +0 -0
  63. data/guides/assets/images/icons/caution.png +0 -0
  64. data/guides/assets/images/icons/example.png +0 -0
  65. data/guides/assets/images/icons/home.png +0 -0
  66. data/guides/assets/images/icons/important.png +0 -0
  67. data/guides/assets/images/icons/next.png +0 -0
  68. data/guides/assets/images/icons/note.png +0 -0
  69. data/guides/assets/images/icons/prev.png +0 -0
  70. data/guides/assets/images/icons/tip.png +0 -0
  71. data/guides/assets/images/icons/up.png +0 -0
  72. data/guides/assets/images/icons/warning.png +0 -0
  73. data/guides/assets/images/nav_arrow.gif +0 -0
  74. data/guides/assets/images/oscardelben.jpg +0 -0
  75. data/guides/assets/images/polymorphic.png +0 -0
  76. data/guides/assets/images/radar.png +0 -0
  77. data/guides/assets/images/rails4_features.png +0 -0
  78. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  79. data/guides/assets/images/rails_guides_logo.gif +0 -0
  80. data/guides/assets/images/rails_logo_remix.gif +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 +0 -59
  90. data/guides/assets/javascripts/jquery.min.js +0 -4
  91. data/guides/assets/javascripts/responsive-tables.js +0 -43
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  118. data/guides/assets/stylesheets/fixes.css +0 -16
  119. data/guides/assets/stylesheets/kindle.css +0 -11
  120. data/guides/assets/stylesheets/main.css +0 -713
  121. data/guides/assets/stylesheets/print.css +0 -52
  122. data/guides/assets/stylesheets/reset.css +0 -43
  123. data/guides/assets/stylesheets/responsive-tables.css +0 -50
  124. data/guides/assets/stylesheets/style.css +0 -13
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  143. data/guides/bug_report_templates/action_controller_gem.rb +0 -47
  144. data/guides/bug_report_templates/action_controller_master.rb +0 -54
  145. data/guides/bug_report_templates/active_record_gem.rb +0 -40
  146. data/guides/bug_report_templates/active_record_master.rb +0 -49
  147. data/guides/bug_report_templates/generic_gem.rb +0 -15
  148. data/guides/bug_report_templates/generic_master.rb +0 -26
  149. data/guides/rails_guides/generator.rb +0 -248
  150. data/guides/rails_guides/helpers.rb +0 -53
  151. data/guides/rails_guides/indexer.rb +0 -68
  152. data/guides/rails_guides/kindle.rb +0 -119
  153. data/guides/rails_guides/levenshtein.rb +0 -37
  154. data/guides/rails_guides/markdown/renderer.rb +0 -82
  155. data/guides/rails_guides/markdown.rb +0 -167
  156. data/guides/rails_guides.rb +0 -63
  157. data/guides/source/2_2_release_notes.md +0 -435
  158. data/guides/source/2_3_release_notes.md +0 -621
  159. data/guides/source/3_0_release_notes.md +0 -611
  160. data/guides/source/3_1_release_notes.md +0 -559
  161. data/guides/source/3_2_release_notes.md +0 -568
  162. data/guides/source/4_0_release_notes.md +0 -279
  163. data/guides/source/4_1_release_notes.md +0 -730
  164. data/guides/source/4_2_release_notes.md +0 -877
  165. data/guides/source/_license.html.erb +0 -2
  166. data/guides/source/_welcome.html.erb +0 -23
  167. data/guides/source/action_controller_overview.md +0 -1192
  168. data/guides/source/action_mailer_basics.md +0 -757
  169. data/guides/source/action_view_overview.md +0 -1561
  170. data/guides/source/active_job_basics.md +0 -339
  171. data/guides/source/active_model_basics.md +0 -554
  172. data/guides/source/active_record_basics.md +0 -374
  173. data/guides/source/active_record_callbacks.md +0 -413
  174. data/guides/source/active_record_migrations.md +0 -1018
  175. data/guides/source/active_record_postgresql.md +0 -433
  176. data/guides/source/active_record_querying.md +0 -1781
  177. data/guides/source/active_record_validations.md +0 -1179
  178. data/guides/source/active_support_core_extensions.md +0 -3857
  179. data/guides/source/active_support_instrumentation.md +0 -488
  180. data/guides/source/api_documentation_guidelines.md +0 -361
  181. data/guides/source/asset_pipeline.md +0 -1304
  182. data/guides/source/association_basics.md +0 -2245
  183. data/guides/source/autoloading_and_reloading_constants.md +0 -1311
  184. data/guides/source/caching_with_rails.md +0 -379
  185. data/guides/source/command_line.md +0 -625
  186. data/guides/source/configuring.md +0 -1072
  187. data/guides/source/contributing_to_ruby_on_rails.md +0 -628
  188. data/guides/source/credits.html.erb +0 -80
  189. data/guides/source/debugging_rails_applications.md +0 -861
  190. data/guides/source/development_dependencies_install.md +0 -289
  191. data/guides/source/documents.yaml +0 -205
  192. data/guides/source/engines.md +0 -1412
  193. data/guides/source/form_helpers.md +0 -1024
  194. data/guides/source/generators.md +0 -676
  195. data/guides/source/getting_started.md +0 -2086
  196. data/guides/source/i18n.md +0 -1087
  197. data/guides/source/index.html.erb +0 -28
  198. data/guides/source/initialization.md +0 -704
  199. data/guides/source/kindle/copyright.html.erb +0 -1
  200. data/guides/source/kindle/layout.html.erb +0 -27
  201. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  202. data/guides/source/kindle/toc.html.erb +0 -24
  203. data/guides/source/kindle/toc.ncx.erb +0 -64
  204. data/guides/source/kindle/welcome.html.erb +0 -5
  205. data/guides/source/layout.html.erb +0 -140
  206. data/guides/source/layouts_and_rendering.md +0 -1227
  207. data/guides/source/maintenance_policy.md +0 -78
  208. data/guides/source/nested_model_forms.md +0 -228
  209. data/guides/source/plugins.md +0 -444
  210. data/guides/source/rails_application_templates.md +0 -266
  211. data/guides/source/rails_on_rack.md +0 -336
  212. data/guides/source/routing.md +0 -1155
  213. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -127
  214. data/guides/source/security.md +0 -1024
  215. data/guides/source/testing.md +0 -1132
  216. data/guides/source/upgrading_ruby_on_rails.md +0 -1186
  217. data/guides/source/working_with_javascript_in_rails.md +0 -407
  218. data/guides/w3c_validator.rb +0 -97
@@ -1,1179 +0,0 @@
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
- $ bin/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` just returns the object.
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.messages` instance method, which returns a collection of errors.
166
- By 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.messages
180
- # => {}
181
-
182
- >> p.valid?
183
- # => false
184
- >> p.errors.messages
185
- # => {name:["can't be blank"]}
186
-
187
- >> p = Person.create
188
- # => #<Person id: nil, name: nil>
189
- >> p.errors.messages
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
- `: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: "%{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 allows letters" }
361
- end
362
- ```
363
-
364
- Alternatively, you can require that the specified attribute does _not_ match the regular expression by using the `:without` option.
365
-
366
- The default error message is _"is invalid"_.
367
-
368
- ### `inclusion`
369
-
370
- This helper validates that the attributes' values are included in a given set.
371
- In fact, this set can be any enumerable object.
372
-
373
- ```ruby
374
- class Coffee < ActiveRecord::Base
375
- validates :size, inclusion: { in: %w(small medium large),
376
- message: "%{value} is not a valid size" }
377
- end
378
- ```
379
-
380
- The `inclusion` helper has an option `:in` that receives the set of values that
381
- will be accepted. The `:in` option has an alias called `:within` that you can
382
- use for the same purpose, if you'd like to. The previous example uses the
383
- `:message` option to show how you can include the attribute's value.
384
-
385
- The default error message for this helper is _"is not included in the list"_.
386
-
387
- ### `length`
388
-
389
- This helper validates the length of the attributes' values. It provides a
390
- variety of options, so you can specify length constraints in different ways:
391
-
392
- ```ruby
393
- class Person < ActiveRecord::Base
394
- validates :name, length: { minimum: 2 }
395
- validates :bio, length: { maximum: 500 }
396
- validates :password, length: { in: 6..20 }
397
- validates :registration_number, length: { is: 6 }
398
- end
399
- ```
400
-
401
- The possible length constraint options are:
402
-
403
- * `:minimum` - The attribute cannot have less than the specified length.
404
- * `:maximum` - The attribute cannot have more than the specified length.
405
- * `:in` (or `:within`) - The attribute length must be included in a given
406
- interval. The value for this option must be a range.
407
- * `:is` - The attribute length must be equal to the given value.
408
-
409
- The default error messages depend on the type of length validation being
410
- performed. You can personalize these messages using the `:wrong_length`,
411
- `:too_long`, and `:too_short` options and `%{count}` as a placeholder for the
412
- number corresponding to the length constraint being used. You can still use the
413
- `:message` option to specify an error message.
414
-
415
- ```ruby
416
- class Person < ActiveRecord::Base
417
- validates :bio, length: { maximum: 1000,
418
- too_long: "%{count} characters is the maximum allowed" }
419
- end
420
- ```
421
-
422
- This helper counts characters by default, but you can split the value in a
423
- different way using the `:tokenizer` option:
424
-
425
- ```ruby
426
- class Essay < ActiveRecord::Base
427
- validates :content, length: {
428
- minimum: 300,
429
- maximum: 400,
430
- tokenizer: lambda { |str| str.split(/\s+/) },
431
- too_short: "must have at least %{count} words",
432
- too_long: "must have at most %{count} words"
433
- }
434
- end
435
- ```
436
-
437
- Note that the default error messages are plural (e.g., "is too short (minimum
438
- is %{count} characters)"). For this reason, when `:minimum` is 1 you should
439
- provide a personalized message or use `presence: true` instead. When
440
- `:in` or `:within` have a lower limit of 1, you should either provide a
441
- personalized message or call `presence` prior to `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 one of the following validations:
530
-
531
- ```ruby
532
- validates :boolean_field_name, presence: true
533
- validates :boolean_field_name, inclusion: { in: [true, false] }
534
- validates :boolean_field_name, exclusion: { in: [nil] }
535
- ```
536
-
537
- By using one of these validations, you will ensure the value will NOT be `nil`
538
- which would result in a `NULL` value in most cases.
539
-
540
- ### `absence`
541
-
542
- This helper validates that the specified attributes are absent. It uses the
543
- `present?` method to check if the value is not either nil or a blank string, that
544
- is, a string that is either empty or consists of whitespace.
545
-
546
- ```ruby
547
- class Person < ActiveRecord::Base
548
- validates :name, :login, :email, absence: true
549
- end
550
- ```
551
-
552
- If you want to be sure that an association is absent, you'll need to test
553
- whether the associated object itself is absent, and not the foreign key used
554
- to map the association.
555
-
556
- ```ruby
557
- class LineItem < ActiveRecord::Base
558
- belongs_to :order
559
- validates :order, absence: true
560
- end
561
- ```
562
-
563
- In order to validate associated records whose absence is required, you must
564
- specify the `:inverse_of` option for the association:
565
-
566
- ```ruby
567
- class Order < ActiveRecord::Base
568
- has_many :line_items, inverse_of: :order
569
- end
570
- ```
571
-
572
- If you validate the absence of an object associated via a `has_one` or
573
- `has_many` relationship, it will check that the object is neither `present?` nor
574
- `marked_for_destruction?`.
575
-
576
- Since `false.present?` is false, if you want to validate the absence of a boolean
577
- field you should use `validates :field_name, exclusion: { in: [true, false] }`.
578
-
579
- The default error message is _"must be blank"_.
580
-
581
- ### `uniqueness`
582
-
583
- This helper validates that the attribute's value is unique right before the
584
- object gets saved. It does not create a uniqueness constraint in the database,
585
- so it may happen that two different database connections create two records
586
- with the same value for a column that you intend to be unique. To avoid that,
587
- you must create a unique index on both columns in your database. See
588
- [the MySQL manual](http://dev.mysql.com/doc/refman/5.6/en/multiple-column-indexes.html)
589
- for more details about multiple column indexes.
590
-
591
- ```ruby
592
- class Account < ActiveRecord::Base
593
- validates :email, uniqueness: true
594
- end
595
- ```
596
-
597
- The validation happens by performing an SQL query into the model's table,
598
- searching for an existing record with the same value in that attribute.
599
-
600
- There is a `:scope` option that you can use to specify other attributes that
601
- are used to limit the uniqueness check:
602
-
603
- ```ruby
604
- class Holiday < ActiveRecord::Base
605
- validates :name, uniqueness: { scope: :year,
606
- message: "should happen once per year" }
607
- end
608
- ```
609
-
610
- There is also a `:case_sensitive` option that you can use to define whether the
611
- uniqueness constraint will be case sensitive or not. This option defaults to
612
- true.
613
-
614
- ```ruby
615
- class Person < ActiveRecord::Base
616
- validates :name, uniqueness: { case_sensitive: false }
617
- end
618
- ```
619
-
620
- WARNING. Note that some databases are configured to perform case-insensitive
621
- searches anyway.
622
-
623
- The default error message is _"has already been taken"_.
624
-
625
- ### `validates_with`
626
-
627
- This helper passes the record to a separate class for validation.
628
-
629
- ```ruby
630
- class GoodnessValidator < ActiveModel::Validator
631
- def validate(record)
632
- if record.first_name == "Evil"
633
- record.errors[:base] << "This person is evil"
634
- end
635
- end
636
- end
637
-
638
- class Person < ActiveRecord::Base
639
- validates_with GoodnessValidator
640
- end
641
- ```
642
-
643
- NOTE: Errors added to `record.errors[:base]` relate to the state of the record
644
- as a whole, and not to a specific attribute.
645
-
646
- The `validates_with` helper takes a class, or a list of classes to use for
647
- validation. There is no default error message for `validates_with`. You must
648
- manually add errors to the record's errors collection in the validator class.
649
-
650
- To implement the validate method, you must have a `record` parameter defined,
651
- which is the record to be validated.
652
-
653
- Like all other validations, `validates_with` takes the `:if`, `:unless` and
654
- `:on` options. If you pass any other options, it will send those options to the
655
- validator class as `options`:
656
-
657
- ```ruby
658
- class GoodnessValidator < ActiveModel::Validator
659
- def validate(record)
660
- if options[:fields].any?{|field| record.send(field) == "Evil" }
661
- record.errors[:base] << "This person is evil"
662
- end
663
- end
664
- end
665
-
666
- class Person < ActiveRecord::Base
667
- validates_with GoodnessValidator, fields: [:first_name, :last_name]
668
- end
669
- ```
670
-
671
- Note that the validator will be initialized *only once* for the whole application
672
- life cycle, and not on each validation run, so be careful about using instance
673
- variables inside it.
674
-
675
- If your validator is complex enough that you want instance variables, you can
676
- easily use a plain old Ruby object instead:
677
-
678
- ```ruby
679
- class Person < ActiveRecord::Base
680
- validate do |person|
681
- GoodnessValidator.new(person).validate
682
- end
683
- end
684
-
685
- class GoodnessValidator
686
- def initialize(person)
687
- @person = person
688
- end
689
-
690
- def validate
691
- if some_complex_condition_involving_ivars_and_private_methods?
692
- @person.errors[:base] << "This person is evil"
693
- end
694
- end
695
-
696
- # ...
697
- end
698
- ```
699
-
700
- ### `validates_each`
701
-
702
- This helper validates attributes against a block. It doesn't have a predefined
703
- validation function. You should create one using a block, and every attribute
704
- passed to `validates_each` will be tested against it. In the following example,
705
- we don't want names and surnames to begin with lower case.
706
-
707
- ```ruby
708
- class Person < ActiveRecord::Base
709
- validates_each :name, :surname do |record, attr, value|
710
- record.errors.add(attr, 'must start with upper case') if value =~ /\A[[:lower:]]/
711
- end
712
- end
713
- ```
714
-
715
- The block receives the record, the attribute's name and the attribute's value.
716
- You can do anything you like to check for valid data within the block. If your
717
- validation fails, you should add an error message to the model, therefore
718
- making it invalid.
719
-
720
- Common Validation Options
721
- -------------------------
722
-
723
- These are common validation options:
724
-
725
- ### `:allow_nil`
726
-
727
- The `:allow_nil` option skips the validation when the value being validated is
728
- `nil`.
729
-
730
- ```ruby
731
- class Coffee < ActiveRecord::Base
732
- validates :size, inclusion: { in: %w(small medium large),
733
- message: "%{value} is not a valid size" }, allow_nil: true
734
- end
735
- ```
736
-
737
- ### `:allow_blank`
738
-
739
- The `:allow_blank` option is similar to the `:allow_nil` option. This option
740
- will let validation pass if the attribute's value is `blank?`, like `nil` or an
741
- empty string for example.
742
-
743
- ```ruby
744
- class Topic < ActiveRecord::Base
745
- validates :title, length: { is: 5 }, allow_blank: true
746
- end
747
-
748
- Topic.create(title: "").valid? # => true
749
- Topic.create(title: nil).valid? # => true
750
- ```
751
-
752
- ### `:message`
753
-
754
- As you've already seen, the `:message` option lets you specify the message that
755
- will be added to the `errors` collection when validation fails. When this
756
- option is not used, Active Record will use the respective default error message
757
- for each validation helper.
758
-
759
- ### `:on`
760
-
761
- The `:on` option lets you specify when the validation should happen. The
762
- default behavior for all the built-in validation helpers is to be run on save
763
- (both when you're creating a new record and when you're updating it). If you
764
- want to change it, you can use `on: :create` to run the validation only when a
765
- new record is created or `on: :update` to run the validation only when a record
766
- is updated.
767
-
768
- ```ruby
769
- class Person < ActiveRecord::Base
770
- # it will be possible to update email with a duplicated value
771
- validates :email, uniqueness: true, on: :create
772
-
773
- # it will be possible to create the record with a non-numerical age
774
- validates :age, numericality: true, on: :update
775
-
776
- # the default (validates on both create and update)
777
- validates :name, presence: true
778
- end
779
- ```
780
-
781
- Strict Validations
782
- ------------------
783
-
784
- You can also specify validations to be strict and raise
785
- `ActiveModel::StrictValidationFailed` when the object is invalid.
786
-
787
- ```ruby
788
- class Person < ActiveRecord::Base
789
- validates :name, presence: { strict: true }
790
- end
791
-
792
- Person.new.valid? # => ActiveModel::StrictValidationFailed: Name can't be blank
793
- ```
794
-
795
- There is also an ability to pass custom exception to `:strict` option.
796
-
797
- ```ruby
798
- class Person < ActiveRecord::Base
799
- validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
800
- end
801
-
802
- Person.new.valid? # => TokenGenerationException: Token can't be blank
803
- ```
804
-
805
- Conditional Validation
806
- ----------------------
807
-
808
- Sometimes it will make sense to validate an object only when a given predicate
809
- is satisfied. You can do that by using the `:if` and `:unless` options, which
810
- can take a symbol, a string, a `Proc` or an `Array`. You may use the `:if`
811
- option when you want to specify when the validation **should** happen. If you
812
- want to specify when the validation **should not** happen, then you may use the
813
- `:unless` option.
814
-
815
- ### Using a Symbol with `:if` and `:unless`
816
-
817
- You can associate the `:if` and `:unless` options with a symbol corresponding
818
- to the name of a method that will get called right before validation happens.
819
- This is the most commonly used option.
820
-
821
- ```ruby
822
- class Order < ActiveRecord::Base
823
- validates :card_number, presence: true, if: :paid_with_card?
824
-
825
- def paid_with_card?
826
- payment_type == "card"
827
- end
828
- end
829
- ```
830
-
831
- ### Using a String with `:if` and `:unless`
832
-
833
- You can also use a string that will be evaluated using `eval` and needs to
834
- contain valid Ruby code. You should use this option only when the string
835
- represents a really short condition.
836
-
837
- ```ruby
838
- class Person < ActiveRecord::Base
839
- validates :surname, presence: true, if: "name.nil?"
840
- end
841
- ```
842
-
843
- ### Using a Proc with `:if` and `:unless`
844
-
845
- Finally, it's possible to associate `:if` and `:unless` with a `Proc` object
846
- which will be called. Using a `Proc` object gives you the ability to write an
847
- inline condition instead of a separate method. This option is best suited for
848
- one-liners.
849
-
850
- ```ruby
851
- class Account < ActiveRecord::Base
852
- validates :password, confirmation: true,
853
- unless: Proc.new { |a| a.password.blank? }
854
- end
855
- ```
856
-
857
- ### Grouping Conditional validations
858
-
859
- Sometimes it is useful to have multiple validations use one condition, it can
860
- be easily achieved using `with_options`.
861
-
862
- ```ruby
863
- class User < ActiveRecord::Base
864
- with_options if: :is_admin? do |admin|
865
- admin.validates :password, length: { minimum: 10 }
866
- admin.validates :email, presence: true
867
- end
868
- end
869
- ```
870
-
871
- All validations inside of `with_options` block will have automatically passed
872
- the condition `if: :is_admin?`
873
-
874
- ### Combining Validation Conditions
875
-
876
- On the other hand, when multiple conditions define whether or not a validation
877
- should happen, an `Array` can be used. Moreover, you can apply both `:if` and
878
- `:unless` to the same validation.
879
-
880
- ```ruby
881
- class Computer < ActiveRecord::Base
882
- validates :mouse, presence: true,
883
- if: ["market.retail?", :desktop?],
884
- unless: Proc.new { |c| c.trackpad.present? }
885
- end
886
- ```
887
-
888
- The validation only runs when all the `:if` conditions and none of the
889
- `:unless` conditions are evaluated to `true`.
890
-
891
- Performing Custom Validations
892
- -----------------------------
893
-
894
- When the built-in validation helpers are not enough for your needs, you can
895
- write your own validators or validation methods as you prefer.
896
-
897
- ### Custom Validators
898
-
899
- Custom validators are classes that extend `ActiveModel::Validator`. These
900
- classes must implement a `validate` method which takes a record as an argument
901
- and performs the validation on it. The custom validator is called using the
902
- `validates_with` method.
903
-
904
- ```ruby
905
- class MyValidator < ActiveModel::Validator
906
- def validate(record)
907
- unless record.name.starts_with? 'X'
908
- record.errors[:name] << 'Need a name starting with X please!'
909
- end
910
- end
911
- end
912
-
913
- class Person
914
- include ActiveModel::Validations
915
- validates_with MyValidator
916
- end
917
- ```
918
-
919
- The easiest way to add custom validators for validating individual attributes
920
- is with the convenient `ActiveModel::EachValidator`. In this case, the custom
921
- validator class must implement a `validate_each` method which takes three
922
- arguments: record, attribute, and value. These correspond to the instance, the
923
- attribute to be validated, and the value of the attribute in the passed
924
- instance.
925
-
926
- ```ruby
927
- class EmailValidator < ActiveModel::EachValidator
928
- def validate_each(record, attribute, value)
929
- unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
930
- record.errors[attribute] << (options[:message] || "is not an email")
931
- end
932
- end
933
- end
934
-
935
- class Person < ActiveRecord::Base
936
- validates :email, presence: true, email: true
937
- end
938
- ```
939
-
940
- As shown in the example, you can also combine standard validations with your
941
- own custom validators.
942
-
943
- ### Custom Methods
944
-
945
- You can also create methods that verify the state of your models and add
946
- messages to the `errors` collection when they are invalid. You must then
947
- register these methods by using the `validate`
948
- ([API](http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate))
949
- class method, passing in the symbols for the validation methods' names.
950
-
951
- You can pass more than one symbol for each class method and the respective
952
- validations will be run in the same order as they were registered.
953
-
954
- ```ruby
955
- class Invoice < ActiveRecord::Base
956
- validate :expiration_date_cannot_be_in_the_past,
957
- :discount_cannot_be_greater_than_total_value
958
-
959
- def expiration_date_cannot_be_in_the_past
960
- if expiration_date.present? && expiration_date < Date.today
961
- errors.add(:expiration_date, "can't be in the past")
962
- end
963
- end
964
-
965
- def discount_cannot_be_greater_than_total_value
966
- if discount > total_value
967
- errors.add(:discount, "can't be greater than total value")
968
- end
969
- end
970
- end
971
- ```
972
-
973
- By default such validations will run every time you call `valid?`. It is also
974
- possible to control when to run these custom validations by giving an `:on`
975
- option to the `validate` method, with either: `:create` or `:update`.
976
-
977
- ```ruby
978
- class Invoice < ActiveRecord::Base
979
- validate :active_customer, on: :create
980
-
981
- def active_customer
982
- errors.add(:customer_id, "is not active") unless customer.active?
983
- end
984
- end
985
- ```
986
-
987
- Working with Validation Errors
988
- ------------------------------
989
-
990
- 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.
991
-
992
- 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.
993
-
994
- ### `errors`
995
-
996
- 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.
997
-
998
- ```ruby
999
- class Person < ActiveRecord::Base
1000
- validates :name, presence: true, length: { minimum: 3 }
1001
- end
1002
-
1003
- person = Person.new
1004
- person.valid? # => false
1005
- person.errors.messages
1006
- # => {:name=>["can't be blank", "is too short (minimum is 3 characters)"]}
1007
-
1008
- person = Person.new(name: "John Doe")
1009
- person.valid? # => true
1010
- person.errors.messages # => {}
1011
- ```
1012
-
1013
- ### `errors[]`
1014
-
1015
- `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.
1016
-
1017
- ```ruby
1018
- class Person < ActiveRecord::Base
1019
- validates :name, presence: true, length: { minimum: 3 }
1020
- end
1021
-
1022
- person = Person.new(name: "John Doe")
1023
- person.valid? # => true
1024
- person.errors[:name] # => []
1025
-
1026
- person = Person.new(name: "JD")
1027
- person.valid? # => false
1028
- person.errors[:name] # => ["is too short (minimum is 3 characters)"]
1029
-
1030
- person = Person.new
1031
- person.valid? # => false
1032
- person.errors[:name]
1033
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
1034
- ```
1035
-
1036
- ### `errors.add`
1037
-
1038
- 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.
1039
-
1040
- ```ruby
1041
- class Person < ActiveRecord::Base
1042
- def a_method_used_for_validation_purposes
1043
- errors.add(:name, "cannot contain the characters !@#%*()_-+=")
1044
- end
1045
- end
1046
-
1047
- person = Person.create(name: "!@#")
1048
-
1049
- person.errors[:name]
1050
- # => ["cannot contain the characters !@#%*()_-+="]
1051
-
1052
- person.errors.full_messages
1053
- # => ["Name cannot contain the characters !@#%*()_-+="]
1054
- ```
1055
-
1056
- Another way to do this is using `[]=` setter
1057
-
1058
- ```ruby
1059
- class Person < ActiveRecord::Base
1060
- def a_method_used_for_validation_purposes
1061
- errors[:name] = "cannot contain the characters !@#%*()_-+="
1062
- end
1063
- end
1064
-
1065
- person = Person.create(name: "!@#")
1066
-
1067
- person.errors[:name]
1068
- # => ["cannot contain the characters !@#%*()_-+="]
1069
-
1070
- person.errors.to_a
1071
- # => ["Name cannot contain the characters !@#%*()_-+="]
1072
- ```
1073
-
1074
- ### `errors[:base]`
1075
-
1076
- 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.
1077
-
1078
- ```ruby
1079
- class Person < ActiveRecord::Base
1080
- def a_method_used_for_validation_purposes
1081
- errors[:base] << "This person is invalid because ..."
1082
- end
1083
- end
1084
- ```
1085
-
1086
- ### `errors.clear`
1087
-
1088
- 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.
1089
-
1090
- ```ruby
1091
- class Person < ActiveRecord::Base
1092
- validates :name, presence: true, length: { minimum: 3 }
1093
- end
1094
-
1095
- person = Person.new
1096
- person.valid? # => false
1097
- person.errors[:name]
1098
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
1099
-
1100
- person.errors.clear
1101
- person.errors.empty? # => true
1102
-
1103
- p.save # => false
1104
-
1105
- p.errors[:name]
1106
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
1107
- ```
1108
-
1109
- ### `errors.size`
1110
-
1111
- The `size` method returns the total number of error messages for the object.
1112
-
1113
- ```ruby
1114
- class Person < ActiveRecord::Base
1115
- validates :name, presence: true, length: { minimum: 3 }
1116
- end
1117
-
1118
- person = Person.new
1119
- person.valid? # => false
1120
- person.errors.size # => 2
1121
-
1122
- person = Person.new(name: "Andrea", email: "andrea@example.com")
1123
- person.valid? # => true
1124
- person.errors.size # => 0
1125
- ```
1126
-
1127
- Displaying Validation Errors in Views
1128
- -------------------------------------
1129
-
1130
- Once you've created a model and added validations, if that model is created via
1131
- a web form, you probably want to display an error message when one of the
1132
- validations fail.
1133
-
1134
- Because every application handles this kind of thing differently, Rails does
1135
- not include any view helpers to help you generate these messages directly.
1136
- However, due to the rich number of methods Rails gives you to interact with
1137
- validations in general, it's fairly easy to build your own. In addition, when
1138
- generating a scaffold, Rails will put some ERB into the `_form.html.erb` that
1139
- it generates that displays the full list of errors on that model.
1140
-
1141
- Assuming we have a model that's been saved in an instance variable named
1142
- `@article`, it looks like this:
1143
-
1144
- ```ruby
1145
- <% if @article.errors.any? %>
1146
- <div id="error_explanation">
1147
- <h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>
1148
-
1149
- <ul>
1150
- <% @article.errors.full_messages.each do |msg| %>
1151
- <li><%= msg %></li>
1152
- <% end %>
1153
- </ul>
1154
- </div>
1155
- <% end %>
1156
- ```
1157
-
1158
- Furthermore, if you use the Rails form helpers to generate your forms, when
1159
- a validation error occurs on a field, it will generate an extra `<div>` around
1160
- the entry.
1161
-
1162
- ```
1163
- <div class="field_with_errors">
1164
- <input id="article_title" name="article[title]" size="30" type="text" value="">
1165
- </div>
1166
- ```
1167
-
1168
- You can then style this div however you'd like. The default scaffold that
1169
- Rails generates, for example, adds this CSS rule:
1170
-
1171
- ```
1172
- .field_with_errors {
1173
- padding: 2px;
1174
- background-color: red;
1175
- display: table;
1176
- }
1177
- ```
1178
-
1179
- This means that any field with an error ends up with a 2 pixel red border.