railties 3.0.0.beta

Sign up to get free protection for your applications and to get access to all the features.
Files changed (334) hide show
  1. data/CHANGELOG +2201 -0
  2. data/README +286 -0
  3. data/bin/rails +11 -0
  4. data/builtin/rails_info/rails/info.rb +147 -0
  5. data/builtin/rails_info/rails/info_controller.rb +15 -0
  6. data/builtin/rails_info/rails/info_helper.rb +2 -0
  7. data/builtin/routes.rb +3 -0
  8. data/guides/files/javascripts/code_highlighter.js +188 -0
  9. data/guides/files/javascripts/guides.js +7 -0
  10. data/guides/files/javascripts/highlighters.js +90 -0
  11. data/guides/files/stylesheets/main.css +441 -0
  12. data/guides/files/stylesheets/print.css +52 -0
  13. data/guides/files/stylesheets/reset.css +43 -0
  14. data/guides/files/stylesheets/style.css +13 -0
  15. data/guides/files/stylesheets/syntax.css +31 -0
  16. data/guides/images/belongs_to.png +0 -0
  17. data/guides/images/book_icon.gif +0 -0
  18. data/guides/images/bullet.gif +0 -0
  19. data/guides/images/chapters_icon.gif +0 -0
  20. data/guides/images/check_bullet.gif +0 -0
  21. data/guides/images/credits_pic_blank.gif +0 -0
  22. data/guides/images/csrf.png +0 -0
  23. data/guides/images/customized_error_messages.png +0 -0
  24. data/guides/images/error_messages.png +0 -0
  25. data/guides/images/feature_tile.gif +0 -0
  26. data/guides/images/footer_tile.gif +0 -0
  27. data/guides/images/fxn.png +0 -0
  28. data/guides/images/grey_bullet.gif +0 -0
  29. data/guides/images/habtm.png +0 -0
  30. data/guides/images/has_many.png +0 -0
  31. data/guides/images/has_many_through.png +0 -0
  32. data/guides/images/has_one.png +0 -0
  33. data/guides/images/has_one_through.png +0 -0
  34. data/guides/images/header_backdrop.png +0 -0
  35. data/guides/images/header_tile.gif +0 -0
  36. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  37. data/guides/images/i18n/demo_translated_en.png +0 -0
  38. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  39. data/guides/images/i18n/demo_translation_missing.png +0 -0
  40. data/guides/images/i18n/demo_untranslated.png +0 -0
  41. data/guides/images/icons/README +5 -0
  42. data/guides/images/icons/callouts/1.png +0 -0
  43. data/guides/images/icons/callouts/10.png +0 -0
  44. data/guides/images/icons/callouts/11.png +0 -0
  45. data/guides/images/icons/callouts/12.png +0 -0
  46. data/guides/images/icons/callouts/13.png +0 -0
  47. data/guides/images/icons/callouts/14.png +0 -0
  48. data/guides/images/icons/callouts/15.png +0 -0
  49. data/guides/images/icons/callouts/2.png +0 -0
  50. data/guides/images/icons/callouts/3.png +0 -0
  51. data/guides/images/icons/callouts/4.png +0 -0
  52. data/guides/images/icons/callouts/5.png +0 -0
  53. data/guides/images/icons/callouts/6.png +0 -0
  54. data/guides/images/icons/callouts/7.png +0 -0
  55. data/guides/images/icons/callouts/8.png +0 -0
  56. data/guides/images/icons/callouts/9.png +0 -0
  57. data/guides/images/icons/caution.png +0 -0
  58. data/guides/images/icons/example.png +0 -0
  59. data/guides/images/icons/home.png +0 -0
  60. data/guides/images/icons/important.png +0 -0
  61. data/guides/images/icons/next.png +0 -0
  62. data/guides/images/icons/note.png +0 -0
  63. data/guides/images/icons/prev.png +0 -0
  64. data/guides/images/icons/tip.png +0 -0
  65. data/guides/images/icons/up.png +0 -0
  66. data/guides/images/icons/warning.png +0 -0
  67. data/guides/images/nav_arrow.gif +0 -0
  68. data/guides/images/polymorphic.png +0 -0
  69. data/guides/images/posts_index.png +0 -0
  70. data/guides/images/rails_guides_logo.gif +0 -0
  71. data/guides/images/rails_logo_remix.gif +0 -0
  72. data/guides/images/rails_welcome.png +0 -0
  73. data/guides/images/session_fixation.png +0 -0
  74. data/guides/images/tab_grey.gif +0 -0
  75. data/guides/images/tab_info.gif +0 -0
  76. data/guides/images/tab_note.gif +0 -0
  77. data/guides/images/tab_red.gif +0 -0
  78. data/guides/images/tab_yellow.gif +0 -0
  79. data/guides/images/tab_yellow.png +0 -0
  80. data/guides/images/validation_error_messages.png +0 -0
  81. data/guides/rails_guides.rb +44 -0
  82. data/guides/rails_guides/generator.rb +178 -0
  83. data/guides/rails_guides/helpers.rb +34 -0
  84. data/guides/rails_guides/indexer.rb +55 -0
  85. data/guides/rails_guides/levenshtein.rb +31 -0
  86. data/guides/rails_guides/textile_extensions.rb +41 -0
  87. data/guides/source/2_2_release_notes.textile +422 -0
  88. data/guides/source/2_3_release_notes.textile +610 -0
  89. data/guides/source/3_0_release_notes.textile +560 -0
  90. data/guides/source/action_controller_overview.textile +783 -0
  91. data/guides/source/action_mailer_basics.textile +437 -0
  92. data/guides/source/action_view_overview.textile +1481 -0
  93. data/guides/source/active_record_basics.textile +204 -0
  94. data/guides/source/active_record_querying.textile +961 -0
  95. data/guides/source/active_support_core_extensions.textile +1835 -0
  96. data/guides/source/activerecord_validations_callbacks.textile +1127 -0
  97. data/guides/source/ajax_on_rails.textile +342 -0
  98. data/guides/source/association_basics.textile +1816 -0
  99. data/guides/source/caching_with_rails.textile +390 -0
  100. data/guides/source/command_line.textile +589 -0
  101. data/guides/source/configuring.textile +290 -0
  102. data/guides/source/contribute.textile +71 -0
  103. data/guides/source/contributing_to_rails.textile +272 -0
  104. data/guides/source/credits.textile.erb +52 -0
  105. data/guides/source/debugging_rails_applications.textile +709 -0
  106. data/guides/source/form_helpers.textile +768 -0
  107. data/guides/source/generators.textile +378 -0
  108. data/guides/source/getting_started.textile +1310 -0
  109. data/guides/source/i18n.textile +879 -0
  110. data/guides/source/index.textile.erb +124 -0
  111. data/guides/source/layout.html.erb +103 -0
  112. data/guides/source/layouts_and_rendering.textile +979 -0
  113. data/guides/source/migrations.textile +591 -0
  114. data/guides/source/nested_model_forms.textile +222 -0
  115. data/guides/source/performance_testing.textile +531 -0
  116. data/guides/source/plugins.textile +1512 -0
  117. data/guides/source/rails_application_templates.textile +238 -0
  118. data/guides/source/rails_on_rack.textile +306 -0
  119. data/guides/source/routing.textile +903 -0
  120. data/guides/source/security.textile +984 -0
  121. data/guides/source/testing.textile +946 -0
  122. data/lib/generators/erb.rb +8 -0
  123. data/lib/generators/erb/controller/controller_generator.rb +21 -0
  124. data/lib/generators/erb/controller/templates/view.html.erb +2 -0
  125. data/lib/generators/erb/mailer/mailer_generator.rb +20 -0
  126. data/lib/generators/erb/mailer/templates/view.text.erb +3 -0
  127. data/lib/generators/erb/scaffold/scaffold_generator.rb +53 -0
  128. data/lib/generators/erb/scaffold/templates/_form.html.erb +13 -0
  129. data/lib/generators/erb/scaffold/templates/edit.html.erb +6 -0
  130. data/lib/generators/erb/scaffold/templates/index.html.erb +27 -0
  131. data/lib/generators/erb/scaffold/templates/layout.html.erb +16 -0
  132. data/lib/generators/erb/scaffold/templates/new.html.erb +5 -0
  133. data/lib/generators/erb/scaffold/templates/show.html.erb +10 -0
  134. data/lib/generators/rails/app/USAGE +9 -0
  135. data/lib/generators/rails/app/app_generator.rb +262 -0
  136. data/lib/generators/rails/app/templates/Gemfile +34 -0
  137. data/lib/generators/rails/app/templates/README +243 -0
  138. data/lib/generators/rails/app/templates/Rakefile +10 -0
  139. data/lib/generators/rails/app/templates/app/controllers/application_controller.rb +3 -0
  140. data/lib/generators/rails/app/templates/app/helpers/application_helper.rb +2 -0
  141. data/lib/generators/rails/app/templates/app/models/.empty_directory +0 -0
  142. data/lib/generators/rails/app/templates/app/views/layouts/.empty_directory +0 -0
  143. data/lib/generators/rails/app/templates/config.ru +4 -0
  144. data/lib/generators/rails/app/templates/config/application.rb +51 -0
  145. data/lib/generators/rails/app/templates/config/boot.rb +17 -0
  146. data/lib/generators/rails/app/templates/config/databases/frontbase.yml +28 -0
  147. data/lib/generators/rails/app/templates/config/databases/ibm_db.yml +71 -0
  148. data/lib/generators/rails/app/templates/config/databases/mysql.yml +60 -0
  149. data/lib/generators/rails/app/templates/config/databases/oracle.yml +39 -0
  150. data/lib/generators/rails/app/templates/config/databases/postgresql.yml +51 -0
  151. data/lib/generators/rails/app/templates/config/databases/sqlite3.yml +22 -0
  152. data/lib/generators/rails/app/templates/config/environment.rb +5 -0
  153. data/lib/generators/rails/app/templates/config/environments/development.rb.tt +19 -0
  154. data/lib/generators/rails/app/templates/config/environments/production.rb.tt +33 -0
  155. data/lib/generators/rails/app/templates/config/environments/test.rb.tt +29 -0
  156. data/lib/generators/rails/app/templates/config/initializers/backtrace_silencers.rb +7 -0
  157. data/lib/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt +7 -0
  158. data/lib/generators/rails/app/templates/config/initializers/inflections.rb +10 -0
  159. data/lib/generators/rails/app/templates/config/initializers/mime_types.rb +5 -0
  160. data/lib/generators/rails/app/templates/config/initializers/session_store.rb.tt +15 -0
  161. data/lib/generators/rails/app/templates/config/locales/en.yml +5 -0
  162. data/lib/generators/rails/app/templates/config/routes.rb +58 -0
  163. data/lib/generators/rails/app/templates/db/seeds.rb +7 -0
  164. data/lib/generators/rails/app/templates/doc/README_FOR_APP +2 -0
  165. data/lib/generators/rails/app/templates/gitignore +4 -0
  166. data/lib/generators/rails/app/templates/public/404.html +26 -0
  167. data/lib/generators/rails/app/templates/public/422.html +26 -0
  168. data/lib/generators/rails/app/templates/public/500.html +26 -0
  169. data/lib/generators/rails/app/templates/public/favicon.ico +0 -0
  170. data/lib/generators/rails/app/templates/public/images/rails.png +0 -0
  171. data/lib/generators/rails/app/templates/public/index.html +278 -0
  172. data/lib/generators/rails/app/templates/public/javascripts/application.js +2 -0
  173. data/lib/generators/rails/app/templates/public/javascripts/controls.js +963 -0
  174. data/lib/generators/rails/app/templates/public/javascripts/dragdrop.js +973 -0
  175. data/lib/generators/rails/app/templates/public/javascripts/effects.js +1128 -0
  176. data/lib/generators/rails/app/templates/public/javascripts/prototype.js +4320 -0
  177. data/lib/generators/rails/app/templates/public/javascripts/rails.js +110 -0
  178. data/lib/generators/rails/app/templates/public/robots.txt +5 -0
  179. data/lib/generators/rails/app/templates/public/stylesheets/.empty_directory +0 -0
  180. data/lib/generators/rails/app/templates/script/rails +9 -0
  181. data/lib/generators/rails/app/templates/test/fixtures/.empty_directory +0 -0
  182. data/lib/generators/rails/app/templates/test/functional/.empty_directory +0 -0
  183. data/lib/generators/rails/app/templates/test/integration/.empty_directory +0 -0
  184. data/lib/generators/rails/app/templates/test/performance/browsing_test.rb +9 -0
  185. data/lib/generators/rails/app/templates/test/test_helper.rb +13 -0
  186. data/lib/generators/rails/app/templates/test/unit/.empty_directory +0 -0
  187. data/lib/generators/rails/controller/USAGE +18 -0
  188. data/lib/generators/rails/controller/controller_generator.rb +14 -0
  189. data/lib/generators/rails/controller/templates/controller.rb +7 -0
  190. data/lib/generators/rails/generator/USAGE +11 -0
  191. data/lib/generators/rails/generator/generator_generator.rb +25 -0
  192. data/lib/generators/rails/generator/templates/%file_name%_generator.rb.tt +5 -0
  193. data/lib/generators/rails/generator/templates/USAGE.tt +8 -0
  194. data/lib/generators/rails/generator/templates/templates/.empty_directory +0 -0
  195. data/lib/generators/rails/helper/USAGE +17 -0
  196. data/lib/generators/rails/helper/helper_generator.rb +13 -0
  197. data/lib/generators/rails/helper/templates/helper.rb +2 -0
  198. data/lib/generators/rails/integration_test/USAGE +10 -0
  199. data/lib/generators/rails/integration_test/integration_test_generator.rb +7 -0
  200. data/lib/generators/rails/mailer/USAGE +15 -0
  201. data/lib/generators/rails/mailer/mailer_generator.rb +14 -0
  202. data/lib/generators/rails/mailer/templates/mailer.rb +16 -0
  203. data/lib/generators/rails/metal/USAGE +8 -0
  204. data/lib/generators/rails/metal/metal_generator.rb +11 -0
  205. data/lib/generators/rails/metal/templates/metal.rb +12 -0
  206. data/lib/generators/rails/migration/USAGE +29 -0
  207. data/lib/generators/rails/migration/migration_generator.rb +8 -0
  208. data/lib/generators/rails/model/USAGE +30 -0
  209. data/lib/generators/rails/model/model_generator.rb +8 -0
  210. data/lib/generators/rails/model_subclass/model_subclass_generator.rb +12 -0
  211. data/lib/generators/rails/observer/USAGE +12 -0
  212. data/lib/generators/rails/observer/observer_generator.rb +7 -0
  213. data/lib/generators/rails/performance_test/USAGE +10 -0
  214. data/lib/generators/rails/performance_test/performance_test_generator.rb +7 -0
  215. data/lib/generators/rails/plugin/USAGE +13 -0
  216. data/lib/generators/rails/plugin/plugin_generator.rb +47 -0
  217. data/lib/generators/rails/plugin/templates/MIT-LICENSE.tt +20 -0
  218. data/lib/generators/rails/plugin/templates/README.tt +13 -0
  219. data/lib/generators/rails/plugin/templates/Rakefile.tt +10 -0
  220. data/lib/generators/rails/plugin/templates/init.rb +1 -0
  221. data/lib/generators/rails/plugin/templates/install.rb +1 -0
  222. data/lib/generators/rails/plugin/templates/lib/%file_name%.rb.tt +1 -0
  223. data/lib/generators/rails/plugin/templates/lib/tasks/%file_name%_tasks.rake.tt +4 -0
  224. data/lib/generators/rails/plugin/templates/uninstall.rb +1 -0
  225. data/lib/generators/rails/resource/USAGE +23 -0
  226. data/lib/generators/rails/resource/resource_generator.rb +34 -0
  227. data/lib/generators/rails/scaffold/USAGE +29 -0
  228. data/lib/generators/rails/scaffold/scaffold_generator.rb +13 -0
  229. data/lib/generators/rails/scaffold_controller/USAGE +20 -0
  230. data/lib/generators/rails/scaffold_controller/scaffold_controller_generator.rb +27 -0
  231. data/lib/generators/rails/scaffold_controller/templates/controller.rb +85 -0
  232. data/lib/generators/rails/session_migration/USAGE +8 -0
  233. data/lib/generators/rails/session_migration/session_migration_generator.rb +8 -0
  234. data/lib/generators/rails/stylesheets/USAGE +5 -0
  235. data/lib/generators/rails/stylesheets/stylesheets_generator.rb +9 -0
  236. data/lib/generators/rails/stylesheets/templates/scaffold.css +61 -0
  237. data/lib/generators/test_unit.rb +8 -0
  238. data/lib/generators/test_unit/controller/controller_generator.rb +14 -0
  239. data/lib/generators/test_unit/controller/templates/functional_test.rb +8 -0
  240. data/lib/generators/test_unit/helper/helper_generator.rb +13 -0
  241. data/lib/generators/test_unit/helper/templates/helper_test.rb +4 -0
  242. data/lib/generators/test_unit/integration/integration_generator.rb +13 -0
  243. data/lib/generators/test_unit/integration/templates/integration_test.rb +10 -0
  244. data/lib/generators/test_unit/mailer/mailer_generator.rb +21 -0
  245. data/lib/generators/test_unit/mailer/templates/fixture +3 -0
  246. data/lib/generators/test_unit/mailer/templates/functional_test.rb +22 -0
  247. data/lib/generators/test_unit/model/model_generator.rb +24 -0
  248. data/lib/generators/test_unit/model/templates/fixtures.yml +23 -0
  249. data/lib/generators/test_unit/model/templates/unit_test.rb +8 -0
  250. data/lib/generators/test_unit/observer/observer_generator.rb +13 -0
  251. data/lib/generators/test_unit/observer/templates/unit_test.rb +8 -0
  252. data/lib/generators/test_unit/performance/performance_generator.rb +13 -0
  253. data/lib/generators/test_unit/performance/templates/performance_test.rb +9 -0
  254. data/lib/generators/test_unit/plugin/plugin_generator.rb +13 -0
  255. data/lib/generators/test_unit/plugin/templates/%file_name%_test.rb.tt +8 -0
  256. data/lib/generators/test_unit/plugin/templates/test_helper.rb +3 -0
  257. data/lib/generators/test_unit/scaffold/scaffold_generator.rb +18 -0
  258. data/lib/generators/test_unit/scaffold/templates/functional_test.rb +47 -0
  259. data/lib/rails.rb +95 -0
  260. data/lib/rails/all.rb +14 -0
  261. data/lib/rails/application.rb +125 -0
  262. data/lib/rails/application/bootstrap.rb +85 -0
  263. data/lib/rails/application/configurable.rb +19 -0
  264. data/lib/rails/application/configuration.rb +86 -0
  265. data/lib/rails/application/finisher.rb +49 -0
  266. data/lib/rails/application/metal_loader.rb +50 -0
  267. data/lib/rails/application/railties.rb +31 -0
  268. data/lib/rails/application/routes_reloader.rb +46 -0
  269. data/lib/rails/backtrace_cleaner.rb +54 -0
  270. data/lib/rails/code_statistics.rb +107 -0
  271. data/lib/rails/commands.rb +72 -0
  272. data/lib/rails/commands/application.rb +13 -0
  273. data/lib/rails/commands/console.rb +55 -0
  274. data/lib/rails/commands/dbconsole.rb +104 -0
  275. data/lib/rails/commands/destroy.rb +9 -0
  276. data/lib/rails/commands/generate.rb +9 -0
  277. data/lib/rails/commands/performance/benchmarker.rb +23 -0
  278. data/lib/rails/commands/performance/profiler.rb +46 -0
  279. data/lib/rails/commands/plugin.rb +542 -0
  280. data/lib/rails/commands/runner.rb +51 -0
  281. data/lib/rails/commands/server.rb +75 -0
  282. data/lib/rails/commands/update.rb +9 -0
  283. data/lib/rails/configuration.rb +191 -0
  284. data/lib/rails/console/app.rb +33 -0
  285. data/lib/rails/console/helpers.rb +5 -0
  286. data/lib/rails/console/sandbox.rb +6 -0
  287. data/lib/rails/deprecation.rb +62 -0
  288. data/lib/rails/dispatcher.rb +24 -0
  289. data/lib/rails/engine.rb +130 -0
  290. data/lib/rails/engine/configurable.rb +25 -0
  291. data/lib/rails/engine/configuration.rb +49 -0
  292. data/lib/rails/generators.rb +289 -0
  293. data/lib/rails/generators/actions.rb +309 -0
  294. data/lib/rails/generators/active_model.rb +78 -0
  295. data/lib/rails/generators/base.rb +362 -0
  296. data/lib/rails/generators/generated_attribute.rb +48 -0
  297. data/lib/rails/generators/migration.rb +64 -0
  298. data/lib/rails/generators/named_base.rb +95 -0
  299. data/lib/rails/generators/resource_helpers.rb +80 -0
  300. data/lib/rails/generators/test_case.rb +239 -0
  301. data/lib/rails/initializable.rb +97 -0
  302. data/lib/rails/paths.rb +144 -0
  303. data/lib/rails/performance_test_help.rb +3 -0
  304. data/lib/rails/plugin.rb +64 -0
  305. data/lib/rails/rack.rb +8 -0
  306. data/lib/rails/rack/debugger.rb +23 -0
  307. data/lib/rails/rack/log_tailer.rb +33 -0
  308. data/lib/rails/rack/logger.rb +34 -0
  309. data/lib/rails/rack/static.rb +5 -0
  310. data/lib/rails/railtie.rb +74 -0
  311. data/lib/rails/railtie/configurable.rb +23 -0
  312. data/lib/rails/railtie/configuration.rb +9 -0
  313. data/lib/rails/railties_path.rb +1 -0
  314. data/lib/rails/ruby_version_check.rb +10 -0
  315. data/lib/rails/rubyprof_ext.rb +35 -0
  316. data/lib/rails/source_annotation_extractor.rb +102 -0
  317. data/lib/rails/subscriber.rb +108 -0
  318. data/lib/rails/subscriber/test_helper.rb +98 -0
  319. data/lib/rails/tasks.rb +16 -0
  320. data/lib/rails/tasks/annotations.rake +20 -0
  321. data/lib/rails/tasks/documentation.rake +96 -0
  322. data/lib/rails/tasks/framework.rake +69 -0
  323. data/lib/rails/tasks/log.rake +9 -0
  324. data/lib/rails/tasks/middleware.rake +7 -0
  325. data/lib/rails/tasks/misc.rake +71 -0
  326. data/lib/rails/tasks/routes.rake +17 -0
  327. data/lib/rails/tasks/statistics.rake +16 -0
  328. data/lib/rails/tasks/tmp.rake +37 -0
  329. data/lib/rails/test_help.rb +30 -0
  330. data/lib/rails/test_unit/railtie.rb +17 -0
  331. data/lib/rails/test_unit/testing.rake +130 -0
  332. data/lib/rails/version.rb +9 -0
  333. data/lib/rails/webrick_server.rb +156 -0
  334. metadata +427 -0
@@ -0,0 +1,1127 @@
1
+ h2. Active Record Validations and Callbacks
2
+
3
+ This guide teaches you how to hook into the lifecycle of your Active Record objects. You will learn how to validate the state of objects before they go into the database, and how to perform custom operations at certain points in the object lifecycle.
4
+
5
+ After reading this guide and trying out the presented concepts, we hope that you'll be able to:
6
+
7
+ * Understand the lifecycle of Active Record objects
8
+ * Use the built-in Active Record validation helpers
9
+ * Create your own custom validation methods
10
+ * Work with the error messages generated by the validation process
11
+ * Create callback methods that respond to events in the object lifecycle
12
+ * Create special classes that encapsulate common behavior for your callbacks
13
+ * Create Observers that respond to lifecycle events outside of the original class
14
+
15
+ endprologue.
16
+
17
+ h3. The Object Lifecycle
18
+
19
+ During the normal operation of a Rails application objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object lifecycle</em> so that you can control your application and its data.
20
+
21
+ Validations allow you to ensure that only valid data is stored in your database. Callbacks and observers allow you to trigger logic before or after an alteration of an object's state.
22
+
23
+ h3. Validations Overview
24
+
25
+ Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture.
26
+
27
+ h4. Why Use Validations?
28
+
29
+ Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address.
30
+
31
+ There are several ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations, and model-level validations.
32
+
33
+ * Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.
34
+ * Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site.
35
+ * Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it's a good idea to "keep your controllers skinny":http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model, as it will make your application a pleasure to work with in the long run.
36
+ * Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well.
37
+
38
+ h4. When Does Validation Happen?
39
+
40
+ There are two kinds of Active Record objects: those that correspond to a row inside your database and those that do not. When you create a fresh object, for example using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it will be saved into the appropriate database table. Active Record uses the +new_record?+ instance method to determine whether an object is already in the database or not. Consider the following simple Active Record class:
41
+
42
+ <ruby>
43
+ class Person < ActiveRecord::Base
44
+ end
45
+ </ruby>
46
+
47
+ We can see how it works by looking at some script/console output:
48
+
49
+ <shell>
50
+ >> p = Person.new(:name => "John Doe")
51
+ => #<Person id: nil, name: "John Doe", created_at: nil, :updated_at: nil>
52
+ >> p.new_record?
53
+ => true
54
+ >> p.save
55
+ => true
56
+ >> p.new_record?
57
+ => false
58
+ </shell>
59
+
60
+ Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
61
+
62
+ CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.
63
+
64
+ The following methods trigger validations, and will save the object to the database only if the object is valid:
65
+
66
+ * +create+
67
+ * +create!+
68
+ * +save+
69
+ * +save!+
70
+ * +update+
71
+ * +update_attributes+
72
+ * +update_attributes!+
73
+
74
+ The bang versions (e.g. +save!+) raise an exception if the record is invalid. The non-bang versions don't: +save+ and +update_attributes+ return +false+, +create+ and +update+ just return the object/s.
75
+
76
+ h4. Skipping Validations
77
+
78
+ The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.
79
+
80
+ * +decrement!+
81
+ * +decrement_counter+
82
+ * +increment!+
83
+ * +increment_counter+
84
+ * +toggle!+
85
+ * +update_all+
86
+ * +update_attribute+
87
+ * +update_counters+
88
+
89
+ Note that +save+ also has the ability to skip validations if passed +false+ as argument. This technique should be used with caution.
90
+
91
+ * +save(false)+
92
+
93
+ h4. +valid?+ and +invalid?+
94
+
95
+ To verify whether or not an object is valid, Rails uses the +valid?+ method. You can also use this method on your own. +valid?+ triggers your validations and returns true if no errors were added to the object, and false otherwise.
96
+
97
+ <ruby>
98
+ class Person < ActiveRecord::Base
99
+ validates_presence_of :name
100
+ end
101
+
102
+ Person.create(:name => "John Doe").valid? # => true
103
+ Person.create(:name => nil).valid? # => false
104
+ </ruby>
105
+
106
+ When Active Record is performing validations, any errors found can be accessed through the +errors+ instance method. By definition an object is valid if this collection is empty after running validations.
107
+
108
+ Note that an object instantiated with +new+ will not report errors even if it's technically invalid, because validations are not run when using +new+.
109
+
110
+ <ruby>
111
+ class Person < ActiveRecord::Base
112
+ validates_presence_of :name
113
+ end
114
+
115
+ >> p = Person.new
116
+ => #<Person id: nil, name: nil>
117
+ >> p.errors
118
+ => #<ActiveRecord::Errors..., @errors={}>
119
+
120
+ >> p.valid?
121
+ => false
122
+ >> p.errors
123
+ => #<ActiveRecord::Errors..., @errors={"name"=>["can't be blank"]}>
124
+
125
+ >> p = Person.create
126
+ => #<Person id: nil, name: nil>
127
+ >> p.errors
128
+ => #<ActiveRecord::Errors..., @errors={"name"=>["can't be blank"]}>
129
+
130
+ >> p.save
131
+ => false
132
+
133
+ >> p.save!
134
+ => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
135
+
136
+ >> Person.create!
137
+ => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
138
+ </ruby>
139
+
140
+ +invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations and returns true if any errors were added to the object, and false otherwise.
141
+
142
+ h4. +errors.invalid?+
143
+
144
+ To verify whether or not a particular attribute of an object is valid, you can use the +errors.invalid?+ method. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +ActiveRecord::Base#invalid?+ method explained above because it doesn't verify the validity of the object as a whole. It only checks to see whether there are errors found on an individual attribute of the object.
145
+
146
+ <ruby>
147
+ class Person < ActiveRecord::Base
148
+ validates_presence_of :name
149
+ end
150
+
151
+ >> Person.new.errors.invalid?(:name) # => false
152
+ >> Person.create.errors.invalid?(:name) # => true
153
+ </ruby>
154
+
155
+ We'll cover validation errors in greater depth in the "Working with Validation Errors":#working-with-validation-errors section. For now, let's turn to the built-in validation helpers that Rails provides by default.
156
+
157
+ h3. Validation Helpers
158
+
159
+ Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated.
160
+
161
+ Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.
162
+
163
+ All of them accept the +:on+ and +:message+ options, which define when the validation should be run and what message should be added to the +errors+ collection if it fails, respectively. The +:on+ option takes one of the values +:save+ (the default), +:create+ or +:update+. There is a default error message for each one of the validation helpers. These messages are used when the +:message+ option isn't specified. Let's take a look at each one of the available helpers.
164
+
165
+ h4. +validates_acceptance_of+
166
+
167
+ Validates that a checkbox on the user interface was checked when a form was submitted. This is typically used when the user needs to agree to your application's terms of service, confirm reading some text, or any similar concept. This validation is very specific to web applications and this 'acceptance' does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).
168
+
169
+ <ruby>
170
+ class Person < ActiveRecord::Base
171
+ validates_acceptance_of :terms_of_service
172
+ end
173
+ </ruby>
174
+
175
+ The default error message for +validates_acceptance_of+ is "_must be accepted_".
176
+
177
+ +validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change this.
178
+
179
+ <ruby>
180
+ class Person < ActiveRecord::Base
181
+ validates_acceptance_of :terms_of_service, :accept => 'yes'
182
+ end
183
+ </ruby>
184
+
185
+ h4. +validates_associated+
186
+
187
+ You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, +valid?+ will be called upon each one of the associated objects.
188
+
189
+ <ruby>
190
+ class Library < ActiveRecord::Base
191
+ has_many :books
192
+ validates_associated :books
193
+ end
194
+ </ruby>
195
+
196
+ This validation will work with all of the association types.
197
+
198
+ CAUTION: Don't use +validates_associated+ on both ends of your associations, they would call each other in an infinite loop.
199
+
200
+ The default error message for +validates_associated+ is "_is invalid_". Note that each associated object will contain its own +errors+ collection; errors do not bubble up to the calling model.
201
+
202
+ h4. +validates_confirmation_of+
203
+
204
+ You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with "_confirmation" appended.
205
+
206
+ <ruby>
207
+ class Person < ActiveRecord::Base
208
+ validates_confirmation_of :email
209
+ end
210
+ </ruby>
211
+
212
+ In your view template you could use something like
213
+
214
+ <erb>
215
+ <%= text_field :person, :email %>
216
+ <%= text_field :person, :email_confirmation %>
217
+ </erb>
218
+
219
+ This check is performed only if +email_confirmation+ is not +nil+. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at +validates_presence_of+ later on this guide):
220
+
221
+ <ruby>
222
+ class Person < ActiveRecord::Base
223
+ validates_confirmation_of :email
224
+ validates_presence_of :email_confirmation
225
+ end
226
+ </ruby>
227
+
228
+ The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_".
229
+
230
+ h4. +validates_exclusion_of+
231
+
232
+ This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
233
+
234
+ <ruby>
235
+ class Account < ActiveRecord::Base
236
+ validates_exclusion_of :subdomain, :in => %w(www),
237
+ :message => "Subdomain {{value}} is reserved."
238
+ end
239
+ </ruby>
240
+
241
+ The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. This example uses the +:message+ option to show how you can include the attribute's value.
242
+
243
+ The default error message for +validates_exclusion_of+ is "_is not included in the list_".
244
+
245
+ h4. +validates_format_of+
246
+
247
+ This helper validates the attributes' values by testing whether they match a given regular expresion, which is specified using the +:with+ option.
248
+
249
+ <ruby>
250
+ class Product < ActiveRecord::Base
251
+ validates_format_of :legacy_code, :with => /\A[a-zA-Z]+\z/,
252
+ :message => "Only letters allowed"
253
+ end
254
+ </ruby>
255
+
256
+ The default error message for +validates_format_of+ is "_is invalid_".
257
+
258
+ h4. +validates_inclusion_of+
259
+
260
+ This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
261
+
262
+ <ruby>
263
+ class Coffee < ActiveRecord::Base
264
+ validates_inclusion_of :size, :in => %w(small medium large),
265
+ :message => "{{value}} is not a valid size"
266
+ end
267
+ </ruby>
268
+
269
+ The +validates_inclusion_of+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. The previous example uses the +:message+ option to show how you can include the attribute's value.
270
+
271
+ The default error message for +validates_inclusion_of+ is "_is not included in the list_".
272
+
273
+ h4. +validates_length_of+
274
+
275
+ This helper validates the length of the attributes' values. It provides a variety of options, so you can specify length constraints in different ways:
276
+
277
+ <ruby>
278
+ class Person < ActiveRecord::Base
279
+ validates_length_of :name, :minimum => 2
280
+ validates_length_of :bio, :maximum => 500
281
+ validates_length_of :password, :in => 6..20
282
+ validates_length_of :registration_number, :is => 6
283
+ end
284
+ </ruby>
285
+
286
+ The possible length constraint options are:
287
+
288
+ * +:minimum+ - The attribute cannot have less than the specified length.
289
+ * +:maximum+ - The attribute cannot have more than the specified length.
290
+ * +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a range.
291
+ * +:is+ - The attribute length must be equal to the given value.
292
+
293
+ The default error messages depend on the type of length validation being performed. You can personalize these messages using the +:wrong_length+, +:too_long+, and +:too_short+ options and <tt>{{count}}</tt> as a placeholder for the number corresponding to the length constraint being used. You can still use the +:message+ option to specify an error message.
294
+
295
+ <ruby>
296
+ class Person < ActiveRecord::Base
297
+ validates_length_of :bio, :maximum => 1000,
298
+ :too_long => "{{count}} characters is the maximum allowed"
299
+ end
300
+ </ruby>
301
+
302
+ This helper counts characters by default, but you can split the value in a different way using the +:tokenizer+ option:
303
+
304
+ <ruby>
305
+ class Essay < ActiveRecord::Base
306
+ validates_length_of :content,
307
+ :minimum => 300,
308
+ :maximum => 400,
309
+ :tokenizer => lambda { |str| str.scan(/\w+/) },
310
+ :too_short => "must have at least {{count}} words",
311
+ :too_long => "must have at most {{count}} words"
312
+ end
313
+ </ruby>
314
+
315
+ The +validates_size_of+ helper is an alias for +validates_length_of+.
316
+
317
+ h4. +validates_numericality_of+
318
+
319
+ This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by an integral or floating point number. To specify that only integral numbers are allowed set +:only_integer+ to true.
320
+
321
+ If you set +:only_integer+ to +true+, then it will use the
322
+
323
+ <ruby>
324
+ /\A[+-]?\d+\Z/
325
+ </ruby>
326
+
327
+ regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using +Float+.
328
+
329
+ WARNING. Note that the regular expression above allows a trailing newline character.
330
+
331
+ <ruby>
332
+ class Player < ActiveRecord::Base
333
+ validates_numericality_of :points
334
+ validates_numericality_of :games_played, :only_integer => true
335
+ end
336
+ </ruby>
337
+
338
+ Besides +:only_integer+, the +validates_numericality_of+ helper also accepts the following options to add constraints to acceptable values:
339
+
340
+ * +:greater_than+ - Specifies the value must be greater than the supplied value. The default error message for this option is "_must be greater than {{count}}_".
341
+ * +:greater_than_or_equal_to+ - Specifies the value must be greater than or equal to the supplied value. The default error message for this option is "_must be greater than or equal to {{count}}_".
342
+ * +:equal_to+ - Specifies the value must be equal to the supplied value. The default error message for this option is "_must be equal to {{count}}_".
343
+ * +:less_than+ - Specifies the value must be less than the supplied value. The default error message for this option is "_must be less than {{count}}_".
344
+ * +:less_than_or_equal_to+ - Specifies the value must be less than or equal the supplied value. The default error message for this option is "_must be less or equal to {{count}}_".
345
+ * +:odd+ - Specifies the value must be an odd number if set to true. The default error message for this option is "_must be odd_".
346
+ * +:even+ - Specifies the value must be an even number if set to true. The default error message for this option is "_must be even_".
347
+
348
+ The default error message for +validates_numericality_of+ is "_is not a number_".
349
+
350
+ h4. +validates_presence_of+
351
+
352
+ This helper validates that the specified attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or a blank string, that is, a string that is either empty or consists of whitespace.
353
+
354
+ <ruby>
355
+ class Person < ActiveRecord::Base
356
+ validates_presence_of :name, :login, :email
357
+ end
358
+ </ruby>
359
+
360
+ If you want to be sure that an association is present, you'll need to test whether the foreign key used to map the association is present, and not the associated object itself.
361
+
362
+ <ruby>
363
+ class LineItem < ActiveRecord::Base
364
+ belongs_to :order
365
+ validates_presence_of :order_id
366
+ end
367
+ </ruby>
368
+
369
+ Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use +validates_inclusion_of :field_name, :in => [true, false]+.
370
+
371
+ The default error message for +validates_presence_of+ is "_can't be empty_".
372
+
373
+ h4. +validates_uniqueness_of+
374
+
375
+ This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create an unique index in your database.
376
+
377
+ <ruby>
378
+ class Account < ActiveRecord::Base
379
+ validates_uniqueness_of :email
380
+ end
381
+ </ruby>
382
+
383
+ The validation happens by performing a SQL query into the model's table, searching for an existing record with the same value in that attribute.
384
+
385
+ There is a +:scope+ option that you can use to specify other attributes that are used to limit the uniqueness check:
386
+
387
+ <ruby>
388
+ class Holiday < ActiveRecord::Base
389
+ validates_uniqueness_of :name, :scope => :year,
390
+ :message => "should happen once per year"
391
+ end
392
+ </ruby>
393
+
394
+ There is also a +:case_sensitive+ option that you can use to define whether the uniqueness constraint will be case sensitive or not. This option defaults to true.
395
+
396
+ <ruby>
397
+ class Person < ActiveRecord::Base
398
+ validates_uniqueness_of :name, :case_sensitive => false
399
+ end
400
+ </ruby>
401
+
402
+ WARNING. Note that some databases are configured to perform case-insensitive searches anyway.
403
+
404
+ The default error message for +validates_uniqueness_of+ is "_has already been taken_".
405
+
406
+ h4. +validates_with+
407
+
408
+ This helper passes the record to a separate class for validation.
409
+
410
+ <ruby>
411
+ class Person < ActiveRecord::Base
412
+ validates_with GoodnessValidator
413
+ end
414
+
415
+ class GoodnessValidator < ActiveRecord::Validator
416
+ def validate
417
+ if record.first_name == "Evil"
418
+ record.errors[:base] << "This person is evil"
419
+ end
420
+ end
421
+ end
422
+ </ruby>
423
+
424
+ The +validates_with+ helper takes a class, or a list of classes to use for validation. There is no default error message for +validates_with+. You must manually add errors to the record's errors collection in the validator class.
425
+
426
+ The validator class has two attributes by default:
427
+
428
+ * +record+ - the record to be validated
429
+ * +options+ - the extra options that were passed to +validates_with+
430
+
431
+ Like all other validations, +validates_with+ takes the +:if+, +:unless+ and +:on+ options. If you pass any other options, it will send those options to the validator class as +options+:
432
+
433
+ <ruby>
434
+ class Person < ActiveRecord::Base
435
+ validates_with GoodnessValidator, :fields => [:first_name, :last_name]
436
+ end
437
+
438
+ class GoodnessValidator < ActiveRecord::Validator
439
+ def validate
440
+ if options[:fields].any?{|field| record.send(field) == "Evil" }
441
+ record.errors[:base] << "This person is evil"
442
+ end
443
+ end
444
+ end
445
+ </ruby>
446
+
447
+ h4. +validates_each+
448
+
449
+ This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to +validates_each+ will be tested against it. In the following example, we don't want names and surnames to begin with lower case.
450
+
451
+ <ruby>
452
+ class Person < ActiveRecord::Base
453
+ validates_each :name, :surname do |model, attr, value|
454
+ model.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
455
+ end
456
+ end
457
+ </ruby>
458
+
459
+ The block receives the model, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you can add an error message to the model, therefore making it invalid.
460
+
461
+ h3. Common Validation Options
462
+
463
+ There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which are discussed later in "Conditional Validation":#conditional-validation.
464
+
465
+ h4. +:allow_nil+
466
+
467
+ The +:allow_nil+ option skips the validation when the value being validated is +nil+. Using +:allow_nil+ with +validates_presence_of+ allows for +nil+, but any other +blank?+ value will still be rejected.
468
+
469
+ <ruby>
470
+ class Coffee < ActiveRecord::Base
471
+ validates_inclusion_of :size, :in => %w(small medium large),
472
+ :message => "{{value}} is not a valid size", :allow_nil => true
473
+ end
474
+ </ruby>
475
+
476
+ h4. +:allow_blank+
477
+
478
+ The +:allow_blank+ option is similar to the +:allow_nil+ option. This option will let validation pass if the attribute's value is +blank?+, like +nil+ or an empty string for example.
479
+
480
+ <ruby>
481
+ class Topic < ActiveRecord::Base
482
+ validates_length_of :title, :is => 5, :allow_blank => true
483
+ end
484
+
485
+ Topic.create("title" => "").valid? # => true
486
+ Topic.create("title" => nil).valid? # => true
487
+ </ruby>
488
+
489
+ h4. +:message+
490
+
491
+ As you've already seen, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.
492
+
493
+ h4. +:on+
494
+
495
+ The +:on+ option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +:on => :create+ to run the validation only when a new record is created or +:on => :update+ to run the validation only when a record is updated.
496
+
497
+ <ruby>
498
+ class Person < ActiveRecord::Base
499
+ # it will be possible to update email with a duplicated value
500
+ validates_uniqueness_of :email, :on => :create
501
+
502
+ # it will be possible to create the record with a non-numerical age
503
+ validates_numericality_of :age, :on => :update
504
+
505
+ # the default (validates on both create and update)
506
+ validates_presence_of :name, :on => :save
507
+ end
508
+ </ruby>
509
+
510
+ h3. Conditional Validation
511
+
512
+ Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a +Proc+. You may use the +:if+ option when you want to specify when the validation *should* happen. If you want to specify when the validation *should not* happen, then you may use the +:unless+ option.
513
+
514
+ h4. Using a Symbol with +:if+ and +:unless+
515
+
516
+ You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
517
+
518
+ <ruby>
519
+ class Order < ActiveRecord::Base
520
+ validates_presence_of :card_number, :if => :paid_with_card?
521
+
522
+ def paid_with_card?
523
+ payment_type == "card"
524
+ end
525
+ end
526
+ </ruby>
527
+
528
+ h4. Using a String with +:if+ and +:unless+
529
+
530
+ You can also use a string that will be evaluated using +eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
531
+
532
+ <ruby>
533
+ class Person < ActiveRecord::Base
534
+ validates_presence_of :surname, :if => "name.nil?"
535
+ end
536
+ </ruby>
537
+
538
+ h4. Using a Proc with +:if+ and +:unless+
539
+
540
+ Finally, it's possible to associate +:if+ and +:unless+ with a +Proc+ object which will be called. Using a +Proc+ object gives you the ability to write an inline condition instead of a separate method. This option is best suited for one-liners.
541
+
542
+ <ruby>
543
+ class Account < ActiveRecord::Base
544
+ validates_confirmation_of :password,
545
+ :unless => Proc.new { |a| a.password.blank? }
546
+ end
547
+ </ruby>
548
+
549
+ h3. Creating Custom Validation Methods
550
+
551
+ When the built-in validation helpers are not enough for your needs, you can write your own validation methods.
552
+
553
+ Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names.
554
+
555
+ You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.
556
+
557
+ <ruby>
558
+ class Invoice < ActiveRecord::Base
559
+ validate :expiration_date_cannot_be_in_the_past,
560
+ :discount_cannot_be_greater_than_total_value
561
+
562
+ def expiration_date_cannot_be_in_the_past
563
+ errors.add(:expiration_date, "can't be in the past") if
564
+ !expiration_date.blank? and expiration_date < Date.today
565
+ end
566
+
567
+ def discount_cannot_be_greater_than_total_value
568
+ errors.add(:discount, "can't be greater than total value") if
569
+ discount > total_value
570
+ end
571
+ end
572
+ </ruby>
573
+
574
+ You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find useful to express that a certain field corresponds to a set of choices:
575
+
576
+ <ruby>
577
+ ActiveRecord::Base.class_eval do
578
+ def self.validates_as_choice(attr_name, n, options={})
579
+ validates_inclusion_of attr_name, {:in => 1..n}.merge(options)
580
+ end
581
+ end
582
+ </ruby>
583
+
584
+ Simply reopen +ActiveRecord::Base+ and define a class method like that. You'd typically put this code somewhere in +config/initializers+. You can use this helper like this:
585
+
586
+ <ruby>
587
+ class Movie < ActiveRecord::Base
588
+ validates_as_choice :rating, 5
589
+ end
590
+ </ruby>
591
+
592
+ h3. Working with Validation Errors
593
+
594
+ 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.
595
+
596
+ The following is a list of the most commonly used methods. Please refer to the +ActiveRecord::Errors+ documentation for a list of all the available methods.
597
+
598
+ h4. +errors.add_to_base+
599
+
600
+ The +add_to_base+ method lets you add errors 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. +add_to_base+ simply receives a string and uses this as the error message.
601
+
602
+ <ruby>
603
+ class Person < ActiveRecord::Base
604
+ def a_method_used_for_validation_purposes
605
+ errors.add_to_base("This person is invalid because ...")
606
+ end
607
+ end
608
+ </ruby>
609
+
610
+ h4. +errors.add+
611
+
612
+ The +add+ method lets you manually add messages that are related to particular attributes. You can use the +full_messages+ method 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.
613
+
614
+ <ruby>
615
+ class Person < ActiveRecord::Base
616
+ def a_method_used_for_validation_purposes
617
+ errors.add(:name, "cannot contain the characters !@#%*()_-+=")
618
+ end
619
+ end
620
+
621
+ person = Person.create(:name => "!@#")
622
+
623
+ person.errors.on(:name)
624
+ # => "cannot contain the characters !@#%*()_-+="
625
+
626
+ person.errors.full_messages
627
+ # => ["Name cannot contain the characters !@#%*()_-+="]
628
+ </ruby>
629
+
630
+ h4. +errors.on+
631
+
632
+ The +on+ method is used when you want to check the error messages for a specific attribute. It returns different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute +on+ returns +nil+. If there is just one error message for this attribute +on+ returns a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ returns an array of strings, each one with one error message.
633
+
634
+ <ruby>
635
+ class Person < ActiveRecord::Base
636
+ validates_presence_of :name
637
+ validates_length_of :name, :minimum => 3
638
+ end
639
+
640
+ person = Person.new(:name => "John Doe")
641
+ person.valid? # => true
642
+ person.errors.on(:name) # => nil
643
+
644
+ person = Person.new(:name => "JD")
645
+ person.valid? # => false
646
+ person.errors.on(:name)
647
+ # => "is too short (minimum is 3 characters)"
648
+
649
+ person = Person.new
650
+ person.valid? # => false
651
+ person.errors.on(:name)
652
+ # => ["can't be blank", "is too short (minimum is 3 characters)"]
653
+ </ruby>
654
+
655
+ h4. +errors.clear+
656
+
657
+ 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.
658
+
659
+ <ruby>
660
+ class Person < ActiveRecord::Base
661
+ validates_presence_of :name
662
+ validates_length_of :name, :minimum => 3
663
+ end
664
+
665
+ person = Person.new
666
+ person.valid? # => false
667
+ person.errors.on(:name)
668
+ # => ["can't be blank", "is too short (minimum is 3 characters)"]
669
+
670
+ person.errors.clear
671
+ person.errors.empty? # => true
672
+
673
+ p.save # => false
674
+
675
+ p.errors.on(:name)
676
+ # => ["can't be blank", "is too short (minimum is 3 characters)"]
677
+ </ruby>
678
+
679
+ h4. +errors.size+
680
+
681
+ The +size+ method returns the total number of error messages for the object.
682
+
683
+ <ruby>
684
+ class Person < ActiveRecord::Base
685
+ validates_presence_of :name
686
+ validates_length_of :name, :minimum => 3
687
+ validates_presence_of :email
688
+ end
689
+
690
+ person = Person.new
691
+ person.valid? # => false
692
+ person.errors.size # => 3
693
+
694
+ person = Person.new(:name => "Andrea", :email => "andrea@example.com")
695
+ person.valid? # => true
696
+ person.errors.size # => 0
697
+ </ruby>
698
+
699
+ h3. Displaying Validation Errors in the View
700
+
701
+ Rails provides built-in helpers to display the error messages of your models in your view templates.
702
+
703
+ h4. +error_messages+ and +error_messages_for+
704
+
705
+ When creating a form with the +form_for+ helper, you can use the +error_messages+ method on the form builder to render all failed validation messages for the current model instance.
706
+
707
+ <ruby>
708
+ class Product < ActiveRecord::Base
709
+ validates_presence_of :description, :value
710
+ validates_numericality_of :value, :allow_nil => true
711
+ end
712
+ </ruby>
713
+
714
+ <erb>
715
+ <% form_for(@product) do |f| %>
716
+ <%= f.error_messages %>
717
+ <p>
718
+ <%= f.label :description %><br />
719
+ <%= f.text_field :description %>
720
+ </p>
721
+ <p>
722
+ <%= f.label :value %><br />
723
+ <%= f.text_field :value %>
724
+ </p>
725
+ <p>
726
+ <%= f.submit "Create" %>
727
+ </p>
728
+ <% end %>
729
+ </erb>
730
+
731
+ To get the idea, if you submit the form with empty fields you typically get this back, though styles are indeed missing by default:
732
+
733
+ !images/error_messages.png(Error messages)!
734
+
735
+ You can also use the +error_messages_for+ helper to display the error messages of a model assigned to a view template. It's very similar to the previous example and will achieve exactly the same result.
736
+
737
+ <erb>
738
+ <%= error_messages_for :product %>
739
+ </erb>
740
+
741
+ The displayed text for each error message will always be formed by the capitalized name of the attribute that holds the error, followed by the error message itself.
742
+
743
+ Both the +form.error_messages+ and the +error_messages_for+ helpers accept options that let you customize the +div+ element that holds the messages, changing the header text, the message below the header text and the tag used for the element that defines the header.
744
+
745
+ <erb>
746
+ <%= f.error_messages :header_message => "Invalid product!",
747
+ :message => "You'll need to fix the following fields:",
748
+ :header_tag => :h3 %>
749
+ </erb>
750
+
751
+ Which results in the following content
752
+
753
+ !images/customized_error_messages.png(Customized error messages)!
754
+
755
+ If you pass +nil+ to any of these options, it will get rid of the respective section of the +div+.
756
+
757
+ h4. Customizing the Error Messages CSS
758
+
759
+ The selectors to customize the style of error messages are:
760
+
761
+ * +.fieldWithErrors+ - Style for the form fields and labels with errors.
762
+ * +#errorExplanation+ - Style for the +div+ element with the error messages.
763
+ * +#errorExplanation h2+ - Style for the header of the +div+ element.
764
+ * +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element.
765
+ * +#errorExplanation ul li+ - Style for the list items with individual error messages.
766
+
767
+ Scaffolding for example generates +public/stylesheets/scaffold.css+, which defines the red-based style you saw above.
768
+
769
+ The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers.
770
+
771
+ h4. Customizing the Error Messages HTML
772
+
773
+ By default, form fields with errors are displayed enclosed by a +div+ element with the +fieldWithErrors+ CSS class. However, it's possible to override that.
774
+
775
+ The way form fields with errors are treated is defined by +ActionView::Base.field_error_proc+. This is a +Proc+ that receives two parameters:
776
+
777
+ * A string with the HTML tag
778
+ * An instance of +ActionView::Helpers::InstanceTag+.
779
+
780
+ Here is a simple example where we change the Rails behaviour to always display the error messages in front of each of the form fields with errors. The error messages will be enclosed by a +span+ element with a +validation-error+ CSS class. There will be no +div+ element enclosing the +input+ element, so we get rid of that red border around the text field. You can use the +validation-error+ CSS class to style it anyway you want.
781
+
782
+ <ruby>
783
+ ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
784
+ if instance.error_message.kind_of?(Array)
785
+ %(#{html_tag}<span class="validation-error">&nbsp;
786
+ #{instance.error_message.join(',')}</span>)
787
+ else
788
+ %(#{html_tag}<span class="validation-error">&nbsp;
789
+ #{instance.error_message}</span>)
790
+ end
791
+ end
792
+ </ruby>
793
+
794
+ This will result in something like the following:
795
+
796
+ !images/validation_error_messages.png(Validation error messages)!
797
+
798
+ h3. Callbacks Overview
799
+
800
+ Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
801
+
802
+ h4. Callback Registration
803
+
804
+ In order to use the available callbacks, you need to register them. You can do that by implementing them as ordinary methods, and then using a macro-style class method to register them as callbacks.
805
+
806
+ <ruby>
807
+ class User < ActiveRecord::Base
808
+ validates_presence_of :login, :email
809
+
810
+ before_validation :ensure_login_has_a_value
811
+
812
+ protected
813
+ def ensure_login_has_a_value
814
+ if login.nil?
815
+ self.login = email unless email.blank?
816
+ end
817
+ end
818
+ end
819
+ </ruby>
820
+
821
+ The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in just one line.
822
+
823
+ <ruby>
824
+ class User < ActiveRecord::Base
825
+ validates_presence_of :login, :email
826
+
827
+ before_create {|user| user.name = user.login.capitalize
828
+ if user.name.blank?}
829
+ end
830
+ </ruby>
831
+
832
+ It's considered good practice to declare callback methods as being protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.
833
+
834
+ h3. Available Callbacks
835
+
836
+ Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations:
837
+
838
+ h4. Creating an Object
839
+
840
+ * +before_validation+
841
+ * +before_validation_on_create+
842
+ * +after_validation+
843
+ * +after_validation_on_create+
844
+ * +before_save+
845
+ * +before_create+
846
+ * INSERT OPERATION
847
+ * +after_create+
848
+ * +after_save+
849
+
850
+ h4. Updating an Object
851
+
852
+ * +before_validation+
853
+ * +before_validation_on_update+
854
+ * +after_validation+
855
+ * +after_validation_on_update+
856
+ * +before_save+
857
+ * +before_update+
858
+ * UPDATE OPERATION
859
+ * +after_update+
860
+ * +after_save+
861
+
862
+ h4. Destroying an Object
863
+
864
+ * +before_destroy+
865
+ * DELETE OPERATION
866
+ * +after_destroy+
867
+
868
+ WARNING. +after_save+ runs both on create and update, but always _after_ the more specific callbacks +after_create+ and +after_update+, no matter the order in which the macro calls were executed.
869
+
870
+ h4. +after_initialize+ and +after_find+
871
+
872
+ The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by directly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method.
873
+
874
+ The +after_find+ callback will be called whenever Active Record loads a record from the database. +after_find+ is called before +after_initialize+ if both are defined.
875
+
876
+ The +after_initialize+ and +after_find+ callbacks are a bit different from the others. They have no +before_*+ counterparts, and the only way to register them is by defining them as regular methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries.
877
+
878
+ <ruby>
879
+ class User < ActiveRecord::Base
880
+ def after_initialize
881
+ puts "You have initialized an object!"
882
+ end
883
+
884
+ def after_find
885
+ puts "You have found an object!"
886
+ end
887
+ end
888
+
889
+ >> User.new
890
+ You have initialized an object!
891
+ => #<User id: nil>
892
+
893
+ >> User.first
894
+ You have found an object!
895
+ You have initialized an object!
896
+ => #<User id: 1>
897
+ </ruby>
898
+
899
+ h3. Running Callbacks
900
+
901
+ The following methods trigger callbacks:
902
+
903
+ * +create+
904
+ * +create!+
905
+ * +decrement!+
906
+ * +destroy+
907
+ * +destroy_all+
908
+ * +increment!+
909
+ * +save+
910
+ * +save!+
911
+ * +save(false)+
912
+ * +toggle!+
913
+ * +update+
914
+ * +update_attribute+
915
+ * +update_attributes+
916
+ * +update_attributes!+
917
+ * +valid?+
918
+
919
+ Additionally, the +after_find+ callback is triggered by the following finder methods:
920
+
921
+ * +all+
922
+ * +first+
923
+ * +find+
924
+ * +find_all_by_<em>attribute</em>+
925
+ * +find_by_<em>attribute</em>+
926
+ * +find_by_<em>attribute</em>!+
927
+ * +last+
928
+
929
+ The +after_initialize+ callback is triggered every time a new object of the class is initialized.
930
+
931
+ h3. Skipping Callbacks
932
+
933
+ Just as with validations, it's also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
934
+
935
+ * +decrement+
936
+ * +decrement_counter+
937
+ * +delete+
938
+ * +delete_all+
939
+ * +find_by_sql+
940
+ * +increment+
941
+ * +increment_counter+
942
+ * +toggle+
943
+ * +update_all+
944
+ * +update_counters+
945
+
946
+ h3. Halting Execution
947
+
948
+ As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
949
+
950
+ The whole callback chain is wrapped in a transaction. If any before callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued. After callbacks can only accomplish that by raising an exception.
951
+
952
+ WARNING. Raising an arbitrary exception may break code that expects +save+ and friends not to fail like that. The +ActiveRecord::Rollback+ exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised.
953
+
954
+ h3. Relational Callbacks
955
+
956
+ Callbacks work through model relationships, and can even be defined by them. Let's take an example where a user has many posts. In our example, a user's posts should be destroyed if the user is destroyed. So, we'll add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model.
957
+
958
+ <ruby>
959
+ class User < ActiveRecord::Base
960
+ has_many :posts, :dependent => :destroy
961
+ end
962
+
963
+ class Post < ActiveRecord::Base
964
+ after_destroy :log_destroy_action
965
+
966
+ def log_destroy_action
967
+ puts 'Post destroyed'
968
+ end
969
+ end
970
+
971
+ >> user = User.first
972
+ => #<User id: 1>
973
+ >> user.posts.create!
974
+ => #<Post id: 1, user_id: 1>
975
+ >> user.destroy
976
+ Post destroyed
977
+ => #<User id: 1>
978
+ </ruby>
979
+
980
+ h3. Conditional Callbacks
981
+
982
+ Like in validations, we can also make our callbacks conditional, calling them only when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a +Proc+. You may use the +:if+ option when you want to specify when the callback *should* get called. If you want to specify when the callback *should not* be called, then you may use the +:unless+ option.
983
+
984
+ h4. Using +:if+ and +:unless+ with a Symbol
985
+
986
+ You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before the callback. If this method returns +false+ the callback won't be executed. This is the most common option. Using this form of registration it's also possible to register several different methods that should be called to check if the callback should be executed.
987
+
988
+ <ruby>
989
+ class Order < ActiveRecord::Base
990
+ before_save :normalize_card_number, :if => :paid_with_card?
991
+ end
992
+ </ruby>
993
+
994
+ h4. Using +:if+ and +:unless+ with a String
995
+
996
+ You can also use a string that will be evaluated using +eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
997
+
998
+ <ruby>
999
+ class Order < ActiveRecord::Base
1000
+ before_save :normalize_card_number, :if => "paid_with_card?"
1001
+ end
1002
+ </ruby>
1003
+
1004
+ h4. Using +:if+ and +:unless+ with a Proc
1005
+
1006
+ Finally, it's possible to associate +:if+ and +:unless+ with a +Proc+ object. This option is best suited when writing short validation methods, usually one-liners.
1007
+
1008
+ <ruby>
1009
+ class Order < ActiveRecord::Base
1010
+ before_save :normalize_card_number,
1011
+ :if => Proc.new { |order| order.paid_with_card? }
1012
+ end
1013
+ </ruby>
1014
+
1015
+ h4. Multiple Conditions for Callbacks
1016
+
1017
+ When writing conditional callbacks, it's possible to mix both +:if+ and +:unless+ in the same callback declaration.
1018
+
1019
+ <ruby>
1020
+ class Comment < ActiveRecord::Base
1021
+ after_create :send_email_to_author, :if => :author_wants_emails?,
1022
+ :unless => Proc.new { |comment| comment.post.ignore_comments? }
1023
+ end
1024
+ </ruby>
1025
+
1026
+ h3. Callback Classes
1027
+
1028
+ Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
1029
+
1030
+ Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model.
1031
+
1032
+ <ruby>
1033
+ class PictureFileCallbacks
1034
+ def after_destroy(picture_file)
1035
+ File.delete(picture_file.filepath)
1036
+ if File.exists?(picture_file.filepath)
1037
+ end
1038
+ end
1039
+ </ruby>
1040
+
1041
+ When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:
1042
+
1043
+ <ruby>
1044
+ class PictureFile < ActiveRecord::Base
1045
+ after_destroy PictureFileCallbacks.new
1046
+ end
1047
+ </ruby>
1048
+
1049
+ Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method.
1050
+
1051
+ <ruby>
1052
+ class PictureFileCallbacks
1053
+ def self.after_destroy(picture_file)
1054
+ File.delete(picture_file.filepath)
1055
+ if File.exists?(picture_file.filepath)
1056
+ end
1057
+ end
1058
+ </ruby>
1059
+
1060
+ If the callback method is declared this way, it won't be necessary to instantiate a +PictureFileCallbacks+ object.
1061
+
1062
+ <ruby>
1063
+ class PictureFile < ActiveRecord::Base
1064
+ after_destroy PictureFileCallbacks
1065
+ end
1066
+ </ruby>
1067
+
1068
+ You can declare as many callbacks as you want inside your callback classes.
1069
+
1070
+ h3. Observers
1071
+
1072
+ Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add the same functionality outside of a model. For example, it could be argued that a +User+ model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn't directly related to your model, you may want to consider creating an observer instead.
1073
+
1074
+ h4. Creating Observers
1075
+
1076
+ For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we could create an observer to contain this functionality.
1077
+
1078
+ <ruby>
1079
+ class UserObserver < ActiveRecord::Observer
1080
+ def after_create(model)
1081
+ # code to send confirmation email...
1082
+ end
1083
+ end
1084
+ </ruby>
1085
+
1086
+ As with callback classes, the observer's methods receive the observed model as a parameter.
1087
+
1088
+ h4. Registering Observers
1089
+
1090
+ Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/environment.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/environment.rb+ this way:
1091
+
1092
+ <ruby>
1093
+ # Activate observers that should always be running
1094
+ config.active_record.observers = :user_observer
1095
+ </ruby>
1096
+
1097
+ As usual, settings in +config/environments+ take precedence over those in +config/environment.rb+. So, if you prefer that an observer not run in all environments, you can simply register it in a specific environment instead.
1098
+
1099
+ h4. Sharing Observers
1100
+
1101
+ By default, Rails will simply strip "Observer" from an observer's name to find the model it should observe. However, observers can also be used to add behaviour to more than one model, and so it's possible to manually specify the models that our observer should observe.
1102
+
1103
+ <ruby>
1104
+ class MailerObserver < ActiveRecord::Observer
1105
+ observe :registration, :user
1106
+
1107
+ def after_create(model)
1108
+ # code to send confirmation email...
1109
+ end
1110
+ end
1111
+ </ruby>
1112
+
1113
+ In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in +config/environment.rb+ in order to take effect.
1114
+
1115
+ <ruby>
1116
+ # Activate observers that should always be running
1117
+ config.active_record.observers = :mailer_observer
1118
+ </ruby>
1119
+
1120
+ h3. Changelog
1121
+
1122
+ "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
1123
+
1124
+ * March 7, 2009: Callbacks revision by Trevor Turk
1125
+ * February 10, 2009: Observers revision by Trevor Turk
1126
+ * February 5, 2009: Initial revision by Trevor Turk
1127
+ * January 9, 2009: Initial version by "Cássio Marques":credits.html#cmarques