railties 3.2.22.5 → 4.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (450) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +186 -78
  3. data/README.rdoc +4 -2
  4. data/lib/rails.rb +11 -44
  5. data/lib/rails/all.rb +0 -1
  6. data/lib/rails/app_rails_loader.rb +37 -0
  7. data/lib/rails/application.rb +176 -124
  8. data/lib/rails/application/bootstrap.rb +29 -23
  9. data/lib/rails/application/configuration.rb +54 -48
  10. data/lib/rails/application/finisher.rb +8 -12
  11. data/lib/rails/application/routes_reloader.rb +2 -2
  12. data/lib/rails/backtrace_cleaner.rb +1 -16
  13. data/lib/rails/cli.rb +2 -2
  14. data/lib/rails/code_statistics.rb +30 -45
  15. data/lib/rails/code_statistics_calculator.rb +79 -0
  16. data/lib/rails/commands.rb +44 -37
  17. data/lib/rails/commands/application.rb +14 -9
  18. data/lib/rails/commands/console.rb +77 -33
  19. data/lib/rails/commands/dbconsole.rb +115 -64
  20. data/lib/rails/commands/destroy.rb +2 -3
  21. data/lib/rails/commands/generate.rb +2 -3
  22. data/lib/rails/commands/plugin_new.rb +0 -2
  23. data/lib/rails/commands/runner.rb +4 -5
  24. data/lib/rails/commands/server.rb +28 -9
  25. data/lib/rails/commands/update.rb +1 -1
  26. data/lib/rails/configuration.rb +35 -8
  27. data/lib/rails/console/app.rb +0 -4
  28. data/lib/rails/deprecation.rb +19 -0
  29. data/lib/rails/engine.rb +111 -92
  30. data/lib/rails/engine/commands.rb +1 -3
  31. data/lib/rails/engine/configuration.rb +26 -19
  32. data/lib/rails/engine/railties.rb +14 -18
  33. data/lib/rails/generators.rb +30 -50
  34. data/lib/rails/generators/actions.rb +38 -103
  35. data/lib/rails/generators/active_model.rb +14 -6
  36. data/lib/rails/generators/app_base.rb +70 -83
  37. data/lib/rails/generators/base.rb +23 -35
  38. data/lib/rails/generators/css/assets/assets_generator.rb +3 -3
  39. data/lib/rails/generators/css/scaffold/scaffold_generator.rb +3 -3
  40. data/lib/rails/generators/erb.rb +2 -2
  41. data/lib/rails/generators/erb/controller/controller_generator.rb +4 -4
  42. data/lib/rails/generators/erb/mailer/mailer_generator.rb +3 -3
  43. data/lib/rails/generators/erb/scaffold/scaffold_generator.rb +4 -4
  44. data/lib/rails/generators/erb/scaffold/templates/index.html.erb +18 -14
  45. data/lib/rails/generators/erb/scaffold/templates/show.html.erb +1 -1
  46. data/lib/rails/generators/generated_attribute.rb +51 -16
  47. data/lib/rails/generators/js/assets/assets_generator.rb +3 -3
  48. data/lib/rails/generators/migration.rb +1 -5
  49. data/lib/rails/generators/named_base.rb +20 -25
  50. data/lib/rails/generators/rails/app/app_generator.rb +40 -48
  51. data/lib/rails/generators/rails/app/templates/Gemfile +8 -7
  52. data/lib/rails/generators/rails/app/templates/README.rdoc +28 -0
  53. data/lib/rails/generators/rails/app/templates/Rakefile +0 -1
  54. data/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt +2 -1
  55. data/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt +5 -0
  56. data/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt +2 -2
  57. data/lib/rails/generators/rails/app/templates/bin/bundle +2 -0
  58. data/lib/rails/generators/rails/app/templates/bin/rails +3 -0
  59. data/lib/rails/generators/rails/app/templates/bin/rake +3 -0
  60. data/lib/rails/generators/rails/app/templates/config/application.rb +5 -43
  61. data/lib/rails/generators/rails/app/templates/config/boot.rb +0 -2
  62. data/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml +2 -2
  63. data/lib/rails/generators/rails/app/templates/config/databases/mysql.yml +1 -4
  64. data/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +8 -3
  65. data/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml +57 -0
  66. data/lib/rails/generators/rails/app/templates/config/environment.rb +2 -2
  67. data/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt +9 -19
  68. data/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +40 -29
  69. data/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +12 -15
  70. data/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb +4 -0
  71. data/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb +6 -5
  72. data/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt +6 -1
  73. data/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt +1 -6
  74. data/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt +6 -6
  75. data/lib/rails/generators/rails/app/templates/config/locales/en.yml +20 -2
  76. data/lib/rails/generators/rails/app/templates/config/routes.rb +15 -24
  77. data/lib/rails/generators/rails/app/templates/db/seeds.rb.tt +2 -2
  78. data/lib/rails/generators/rails/app/templates/gitignore +3 -2
  79. data/lib/rails/generators/rails/app/templates/public/404.html +2 -1
  80. data/lib/rails/generators/rails/app/templates/public/422.html +1 -1
  81. data/lib/rails/generators/rails/app/templates/public/500.html +2 -1
  82. data/lib/rails/generators/rails/app/templates/public/robots.txt +1 -1
  83. data/lib/rails/generators/rails/app/templates/test/test_helper.rb +3 -1
  84. data/lib/rails/generators/rails/assets/assets_generator.rb +5 -5
  85. data/lib/rails/generators/rails/controller/USAGE +7 -7
  86. data/lib/rails/generators/rails/controller/controller_generator.rb +3 -3
  87. data/lib/rails/generators/rails/controller/templates/controller.rb +1 -1
  88. data/lib/rails/generators/rails/generator/generator_generator.rb +4 -4
  89. data/lib/rails/generators/rails/helper/USAGE +1 -1
  90. data/lib/rails/generators/rails/helper/helper_generator.rb +2 -2
  91. data/lib/rails/generators/rails/integration_test/integration_test_generator.rb +2 -2
  92. data/lib/rails/generators/rails/migration/USAGE +12 -6
  93. data/lib/rails/generators/rails/migration/migration_generator.rb +3 -3
  94. data/lib/rails/generators/rails/model/USAGE +53 -4
  95. data/lib/rails/generators/rails/model/model_generator.rb +3 -3
  96. data/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb +81 -39
  97. data/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec +2 -2
  98. data/lib/rails/generators/rails/plugin_new/templates/Gemfile +16 -1
  99. data/lib/rails/generators/rails/plugin_new/templates/Rakefile +3 -9
  100. data/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt +0 -1
  101. data/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt +1 -1
  102. data/lib/rails/generators/rails/plugin_new/templates/{script → bin}/rails.tt +0 -0
  103. data/lib/rails/generators/rails/plugin_new/templates/gitignore +3 -0
  104. data/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb +1 -1
  105. data/lib/rails/generators/rails/plugin_new/templates/rails/application.rb +0 -1
  106. data/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb +0 -1
  107. data/lib/rails/generators/rails/resource/resource_generator.rb +5 -5
  108. data/lib/rails/generators/rails/resource_route/resource_route_generator.rb +2 -2
  109. data/lib/rails/generators/rails/scaffold/scaffold_generator.rb +11 -7
  110. data/lib/rails/generators/rails/scaffold_controller/USAGE +4 -4
  111. data/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb +9 -7
  112. data/lib/rails/generators/rails/scaffold_controller/templates/controller.rb +27 -48
  113. data/lib/rails/generators/rails/task/task_generator.rb +2 -2
  114. data/lib/rails/generators/rails/task/templates/task.rb +1 -1
  115. data/lib/rails/generators/resource_helpers.rb +3 -5
  116. data/lib/rails/generators/test_case.rb +22 -28
  117. data/lib/rails/generators/test_unit.rb +3 -3
  118. data/lib/rails/generators/test_unit/controller/controller_generator.rb +6 -6
  119. data/lib/rails/generators/test_unit/helper/helper_generator.rb +5 -5
  120. data/lib/rails/generators/test_unit/integration/integration_generator.rb +4 -4
  121. data/lib/rails/generators/test_unit/mailer/mailer_generator.rb +6 -6
  122. data/lib/rails/generators/test_unit/model/model_generator.rb +7 -7
  123. data/lib/rails/generators/test_unit/model/templates/fixtures.yml +8 -2
  124. data/lib/rails/generators/test_unit/plugin/plugin_generator.rb +4 -4
  125. data/lib/rails/generators/test_unit/plugin/templates/test_helper.rb +1 -2
  126. data/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +10 -19
  127. data/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +5 -5
  128. data/lib/rails/info.rb +3 -3
  129. data/lib/rails/info_controller.rb +26 -8
  130. data/lib/rails/initializable.rb +2 -2
  131. data/lib/rails/paths.rb +59 -54
  132. data/lib/rails/rack/debugger.rb +2 -2
  133. data/lib/rails/rack/logger.rb +33 -8
  134. data/lib/rails/railtie.rb +24 -24
  135. data/lib/rails/railtie/configurable.rb +1 -1
  136. data/lib/rails/railtie/configuration.rb +15 -5
  137. data/lib/rails/ruby_version_check.rb +3 -13
  138. data/lib/rails/rubyprof_ext.rb +1 -1
  139. data/lib/rails/source_annotation_extractor.rb +40 -17
  140. data/lib/rails/tasks/annotations.rake +1 -1
  141. data/lib/rails/tasks/documentation.rake +10 -57
  142. data/lib/rails/tasks/engine.rake +1 -1
  143. data/lib/rails/tasks/framework.rake +9 -9
  144. data/lib/rails/tasks/log.rake +18 -4
  145. data/lib/rails/tasks/middleware.rake +1 -1
  146. data/lib/rails/tasks/misc.rake +2 -9
  147. data/lib/rails/tasks/routes.rake +4 -6
  148. data/lib/rails/tasks/statistics.rake +8 -2
  149. data/lib/rails/tasks/tmp.rake +12 -4
  150. data/lib/rails/templates/layouts/application.html.erb +36 -0
  151. data/lib/rails/templates/rails/info/properties.html.erb +1 -0
  152. data/lib/rails/templates/rails/info/routes.html.erb +9 -0
  153. data/lib/rails/{generators/rails/app/templates/public/index.html → templates/rails/welcome/index.html.erb} +18 -14
  154. data/lib/rails/test_help.rb +6 -29
  155. data/lib/rails/test_unit/railtie.rb +2 -3
  156. data/lib/rails/test_unit/testing.rake +45 -33
  157. data/lib/rails/version.rb +4 -4
  158. data/lib/rails/welcome_controller.rb +7 -0
  159. metadata +86 -378
  160. data/guides/assets/images/belongs_to.png +0 -0
  161. data/guides/assets/images/book_icon.gif +0 -0
  162. data/guides/assets/images/bullet.gif +0 -0
  163. data/guides/assets/images/challenge.png +0 -0
  164. data/guides/assets/images/chapters_icon.gif +0 -0
  165. data/guides/assets/images/check_bullet.gif +0 -0
  166. data/guides/assets/images/credits_pic_blank.gif +0 -0
  167. data/guides/assets/images/csrf.png +0 -0
  168. data/guides/assets/images/customized_error_messages.png +0 -0
  169. data/guides/assets/images/edge_badge.png +0 -0
  170. data/guides/assets/images/error_messages.png +0 -0
  171. data/guides/assets/images/feature_tile.gif +0 -0
  172. data/guides/assets/images/footer_tile.gif +0 -0
  173. data/guides/assets/images/fxn.png +0 -0
  174. data/guides/assets/images/grey_bullet.gif +0 -0
  175. data/guides/assets/images/habtm.png +0 -0
  176. data/guides/assets/images/has_many.png +0 -0
  177. data/guides/assets/images/has_many_through.png +0 -0
  178. data/guides/assets/images/has_one.png +0 -0
  179. data/guides/assets/images/has_one_through.png +0 -0
  180. data/guides/assets/images/header_backdrop.png +0 -0
  181. data/guides/assets/images/header_tile.gif +0 -0
  182. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  183. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  184. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  185. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  186. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  187. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  188. data/guides/assets/images/icons/README +0 -5
  189. data/guides/assets/images/icons/callouts/1.png +0 -0
  190. data/guides/assets/images/icons/callouts/10.png +0 -0
  191. data/guides/assets/images/icons/callouts/11.png +0 -0
  192. data/guides/assets/images/icons/callouts/12.png +0 -0
  193. data/guides/assets/images/icons/callouts/13.png +0 -0
  194. data/guides/assets/images/icons/callouts/14.png +0 -0
  195. data/guides/assets/images/icons/callouts/15.png +0 -0
  196. data/guides/assets/images/icons/callouts/2.png +0 -0
  197. data/guides/assets/images/icons/callouts/3.png +0 -0
  198. data/guides/assets/images/icons/callouts/4.png +0 -0
  199. data/guides/assets/images/icons/callouts/5.png +0 -0
  200. data/guides/assets/images/icons/callouts/6.png +0 -0
  201. data/guides/assets/images/icons/callouts/7.png +0 -0
  202. data/guides/assets/images/icons/callouts/8.png +0 -0
  203. data/guides/assets/images/icons/callouts/9.png +0 -0
  204. data/guides/assets/images/icons/caution.png +0 -0
  205. data/guides/assets/images/icons/example.png +0 -0
  206. data/guides/assets/images/icons/home.png +0 -0
  207. data/guides/assets/images/icons/important.png +0 -0
  208. data/guides/assets/images/icons/next.png +0 -0
  209. data/guides/assets/images/icons/note.png +0 -0
  210. data/guides/assets/images/icons/prev.png +0 -0
  211. data/guides/assets/images/icons/tip.png +0 -0
  212. data/guides/assets/images/icons/up.png +0 -0
  213. data/guides/assets/images/icons/warning.png +0 -0
  214. data/guides/assets/images/jaimeiniesta.jpg +0 -0
  215. data/guides/assets/images/nav_arrow.gif +0 -0
  216. data/guides/assets/images/polymorphic.png +0 -0
  217. data/guides/assets/images/posts_index.png +0 -0
  218. data/guides/assets/images/radar.png +0 -0
  219. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  220. data/guides/assets/images/rails_guides_logo.gif +0 -0
  221. data/guides/assets/images/rails_logo_remix.gif +0 -0
  222. data/guides/assets/images/rails_welcome.png +0 -0
  223. data/guides/assets/images/session_fixation.png +0 -0
  224. data/guides/assets/images/tab_grey.gif +0 -0
  225. data/guides/assets/images/tab_info.gif +0 -0
  226. data/guides/assets/images/tab_note.gif +0 -0
  227. data/guides/assets/images/tab_red.gif +0 -0
  228. data/guides/assets/images/tab_yellow.gif +0 -0
  229. data/guides/assets/images/tab_yellow.png +0 -0
  230. data/guides/assets/images/validation_error_messages.png +0 -0
  231. data/guides/assets/images/vijaydev.jpg +0 -0
  232. data/guides/assets/javascripts/guides.js +0 -7
  233. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  234. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  235. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  236. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  237. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  238. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  239. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  240. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  241. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  242. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  243. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  244. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  245. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  246. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  247. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  248. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  249. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  250. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  251. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  252. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  253. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  254. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  255. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  256. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  257. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  258. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  259. data/guides/assets/stylesheets/fixes.css +0 -16
  260. data/guides/assets/stylesheets/kindle.css +0 -11
  261. data/guides/assets/stylesheets/main.css +0 -453
  262. data/guides/assets/stylesheets/print.css +0 -52
  263. data/guides/assets/stylesheets/reset.css +0 -43
  264. data/guides/assets/stylesheets/style.css +0 -13
  265. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  266. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  267. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  268. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  269. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  270. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  271. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  272. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  273. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  274. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  275. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  276. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  277. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  278. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  279. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  280. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  281. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  282. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  283. data/guides/code/getting_started/Gemfile +0 -38
  284. data/guides/code/getting_started/README.rdoc +0 -261
  285. data/guides/code/getting_started/Rakefile +0 -7
  286. data/guides/code/getting_started/app/assets/images/rails.png +0 -0
  287. data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
  288. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
  289. data/guides/code/getting_started/app/assets/javascripts/home.js.coffee +0 -3
  290. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
  291. data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
  292. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
  293. data/guides/code/getting_started/app/assets/stylesheets/home.css.scss +0 -3
  294. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
  295. data/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss +0 -56
  296. data/guides/code/getting_started/app/controllers/application_controller.rb +0 -3
  297. data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -16
  298. data/guides/code/getting_started/app/controllers/home_controller.rb +0 -5
  299. data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -84
  300. data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
  301. data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
  302. data/guides/code/getting_started/app/helpers/home_helper.rb +0 -2
  303. data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -5
  304. data/guides/code/getting_started/app/models/comment.rb +0 -3
  305. data/guides/code/getting_started/app/models/post.rb +0 -11
  306. data/guides/code/getting_started/app/models/tag.rb +0 -3
  307. data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
  308. data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
  309. data/guides/code/getting_started/app/views/home/index.html.erb +0 -2
  310. data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
  311. data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -32
  312. data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -6
  313. data/guides/code/getting_started/app/views/posts/index.html.erb +0 -27
  314. data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
  315. data/guides/code/getting_started/app/views/posts/show.html.erb +0 -31
  316. data/guides/code/getting_started/app/views/tags/_form.html.erb +0 -12
  317. data/guides/code/getting_started/config.ru +0 -4
  318. data/guides/code/getting_started/config/application.rb +0 -59
  319. data/guides/code/getting_started/config/boot.rb +0 -6
  320. data/guides/code/getting_started/config/database.yml +0 -25
  321. data/guides/code/getting_started/config/environment.rb +0 -5
  322. data/guides/code/getting_started/config/environments/development.rb +0 -37
  323. data/guides/code/getting_started/config/environments/production.rb +0 -67
  324. data/guides/code/getting_started/config/environments/test.rb +0 -37
  325. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  326. data/guides/code/getting_started/config/initializers/inflections.rb +0 -15
  327. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  328. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -7
  329. data/guides/code/getting_started/config/initializers/session_store.rb +0 -8
  330. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  331. data/guides/code/getting_started/config/locales/en.yml +0 -5
  332. data/guides/code/getting_started/config/routes.rb +0 -64
  333. data/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb +0 -11
  334. data/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb +0 -12
  335. data/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb +0 -11
  336. data/guides/code/getting_started/db/schema.rb +0 -43
  337. data/guides/code/getting_started/db/seeds.rb +0 -7
  338. data/guides/code/getting_started/doc/README_FOR_APP +0 -2
  339. data/guides/code/getting_started/public/404.html +0 -26
  340. data/guides/code/getting_started/public/422.html +0 -26
  341. data/guides/code/getting_started/public/500.html +0 -25
  342. data/guides/code/getting_started/public/favicon.ico +0 -0
  343. data/guides/code/getting_started/public/robots.txt +0 -5
  344. data/guides/code/getting_started/script/rails +0 -6
  345. data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
  346. data/guides/code/getting_started/test/fixtures/posts.yml +0 -11
  347. data/guides/code/getting_started/test/fixtures/tags.yml +0 -9
  348. data/guides/code/getting_started/test/functional/comments_controller_test.rb +0 -7
  349. data/guides/code/getting_started/test/functional/home_controller_test.rb +0 -9
  350. data/guides/code/getting_started/test/functional/posts_controller_test.rb +0 -49
  351. data/guides/code/getting_started/test/performance/browsing_test.rb +0 -12
  352. data/guides/code/getting_started/test/test_helper.rb +0 -13
  353. data/guides/code/getting_started/test/unit/comment_test.rb +0 -7
  354. data/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb +0 -4
  355. data/guides/code/getting_started/test/unit/helpers/home_helper_test.rb +0 -4
  356. data/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb +0 -4
  357. data/guides/code/getting_started/test/unit/post_test.rb +0 -7
  358. data/guides/code/getting_started/test/unit/tag_test.rb +0 -7
  359. data/guides/rails_guides.rb +0 -50
  360. data/guides/rails_guides/generator.rb +0 -310
  361. data/guides/rails_guides/helpers.rb +0 -45
  362. data/guides/rails_guides/indexer.rb +0 -69
  363. data/guides/rails_guides/levenshtein.rb +0 -31
  364. data/guides/rails_guides/textile_extensions.rb +0 -63
  365. data/guides/source/2_2_release_notes.textile +0 -422
  366. data/guides/source/2_3_release_notes.textile +0 -610
  367. data/guides/source/3_0_release_notes.textile +0 -595
  368. data/guides/source/3_1_release_notes.textile +0 -553
  369. data/guides/source/3_2_release_notes.textile +0 -540
  370. data/guides/source/_license.html.erb +0 -2
  371. data/guides/source/_welcome.html.erb +0 -19
  372. data/guides/source/action_controller_overview.textile +0 -820
  373. data/guides/source/action_mailer_basics.textile +0 -516
  374. data/guides/source/action_view_overview.textile +0 -1497
  375. data/guides/source/active_model_basics.textile +0 -205
  376. data/guides/source/active_record_basics.textile +0 -218
  377. data/guides/source/active_record_querying.textile +0 -1433
  378. data/guides/source/active_record_validations_callbacks.textile +0 -1287
  379. data/guides/source/active_resource_basics.textile +0 -120
  380. data/guides/source/active_support_core_extensions.textile +0 -3715
  381. data/guides/source/api_documentation_guidelines.textile +0 -185
  382. data/guides/source/asset_pipeline.textile +0 -707
  383. data/guides/source/association_basics.textile +0 -1959
  384. data/guides/source/caching_with_rails.textile +0 -437
  385. data/guides/source/command_line.textile +0 -574
  386. data/guides/source/configuring.textile +0 -643
  387. data/guides/source/contributing_to_ruby_on_rails.textile +0 -448
  388. data/guides/source/credits.html.erb +0 -72
  389. data/guides/source/debugging_rails_applications.textile +0 -714
  390. data/guides/source/documents.yaml +0 -157
  391. data/guides/source/engines.textile +0 -618
  392. data/guides/source/form_helpers.textile +0 -798
  393. data/guides/source/generators.textile +0 -621
  394. data/guides/source/getting_started.textile +0 -1931
  395. data/guides/source/i18n.textile +0 -931
  396. data/guides/source/index.html.erb +0 -30
  397. data/guides/source/initialization.textile +0 -1116
  398. data/guides/source/kindle/KINDLE.md +0 -26
  399. data/guides/source/kindle/copyright.html.erb +0 -1
  400. data/guides/source/kindle/layout.html.erb +0 -27
  401. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  402. data/guides/source/kindle/toc.html.erb +0 -24
  403. data/guides/source/kindle/toc.ncx.erb +0 -64
  404. data/guides/source/kindle/welcome.html.erb +0 -5
  405. data/guides/source/layout.html.erb +0 -124
  406. data/guides/source/layouts_and_rendering.textile +0 -1237
  407. data/guides/source/migrations.textile +0 -900
  408. data/guides/source/nested_model_forms.textile +0 -222
  409. data/guides/source/performance_testing.textile +0 -597
  410. data/guides/source/plugins.textile +0 -464
  411. data/guides/source/rails_application_templates.textile +0 -240
  412. data/guides/source/rails_on_rack.textile +0 -236
  413. data/guides/source/routing.textile +0 -885
  414. data/guides/source/ruby_on_rails_guides_guidelines.textile +0 -79
  415. data/guides/source/security.textile +0 -1004
  416. data/guides/source/testing.textile +0 -947
  417. data/guides/w3c_validator.rb +0 -91
  418. data/lib/rails/application/railties.rb +0 -13
  419. data/lib/rails/application/route_inspector.rb +0 -84
  420. data/lib/rails/commands/benchmarker.rb +0 -34
  421. data/lib/rails/commands/plugin.rb +0 -544
  422. data/lib/rails/commands/profiler.rb +0 -33
  423. data/lib/rails/generators/rails/app/templates/README +0 -261
  424. data/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb +0 -3
  425. data/lib/rails/generators/rails/app/templates/app/mailers/.empty_directory +0 -0
  426. data/lib/rails/generators/rails/app/templates/app/models/.empty_directory +0 -0
  427. data/lib/rails/generators/rails/app/templates/doc/README_FOR_APP +0 -2
  428. data/lib/rails/generators/rails/app/templates/public/stylesheets/.empty_directory +0 -0
  429. data/lib/rails/generators/rails/app/templates/script/rails +0 -5
  430. data/lib/rails/generators/rails/app/templates/test/fixtures/.empty_directory +0 -0
  431. data/lib/rails/generators/rails/app/templates/test/functional/.empty_directory +0 -0
  432. data/lib/rails/generators/rails/app/templates/test/integration/.empty_directory +0 -0
  433. data/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb +0 -12
  434. data/lib/rails/generators/rails/app/templates/test/unit/.empty_directory +0 -0
  435. data/lib/rails/generators/rails/generator/templates/templates/.empty_directory +0 -0
  436. data/lib/rails/generators/rails/observer/USAGE +0 -12
  437. data/lib/rails/generators/rails/observer/observer_generator.rb +0 -7
  438. data/lib/rails/generators/rails/performance_test/USAGE +0 -10
  439. data/lib/rails/generators/rails/performance_test/performance_test_generator.rb +0 -7
  440. data/lib/rails/generators/rails/plugin_new/templates/app/mailers/.empty_directory +0 -0
  441. data/lib/rails/generators/rails/plugin_new/templates/app/models/.empty_directory +0 -0
  442. data/lib/rails/generators/rails/session_migration/USAGE +0 -8
  443. data/lib/rails/generators/rails/session_migration/session_migration_generator.rb +0 -8
  444. data/lib/rails/generators/test_unit/observer/observer_generator.rb +0 -13
  445. data/lib/rails/generators/test_unit/observer/templates/unit_test.rb +0 -9
  446. data/lib/rails/generators/test_unit/performance/performance_generator.rb +0 -13
  447. data/lib/rails/generators/test_unit/performance/templates/performance_test.rb +0 -12
  448. data/lib/rails/performance_test_help.rb +0 -3
  449. data/lib/rails/plugin.rb +0 -92
  450. data/lib/rails/script_rails_loader.rb +0 -29
@@ -1,1287 +0,0 @@
1
- h2. Active Record Validations and Callbacks
2
-
3
- This guide teaches you how to hook into the life cycle of your Active Record objects. You will learn how to validate the state of objects before they go into the database, and how to perform custom operations at certain points in the object life cycle.
4
-
5
- After reading this guide and trying out the presented concepts, we hope that you'll be able to:
6
-
7
- * Understand the life cycle 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 life cycle
12
- * Create special classes that encapsulate common behavior for your callbacks
13
- * Create Observers that respond to life cycle events outside of the original class
14
-
15
- endprologue.
16
-
17
- h3. The Object Life Cycle
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 life cycle</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 +rails console+ output:
48
-
49
- <ruby>
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
- </ruby>
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 objects.
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
- * +touch+
86
- * +update_all+
87
- * +update_attribute+
88
- * +update_column+
89
- * +update_counters+
90
-
91
- Note that +save+ also has the ability to skip validations if passed +:validate => false+ as argument. This technique should be used with caution.
92
-
93
- * +save(:validate => false)+
94
-
95
- h4. +valid?+ and +invalid?+
96
-
97
- 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 found in the object, and false otherwise.
98
-
99
- <ruby>
100
- class Person < ActiveRecord::Base
101
- validates :name, :presence => true
102
- end
103
-
104
- Person.create(:name => "John Doe").valid? # => true
105
- Person.create(:name => nil).valid? # => false
106
- </ruby>
107
-
108
- After Active Record has performed validations, any errors found can be accessed through the +errors+ instance method, which returns a collection of errors. By definition, an object is valid if this collection is empty after running validations.
109
-
110
- 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+.
111
-
112
- <ruby>
113
- class Person < ActiveRecord::Base
114
- validates :name, :presence => true
115
- end
116
-
117
- >> p = Person.new
118
- => #<Person id: nil, name: nil>
119
- >> p.errors
120
- => {}
121
-
122
- >> p.valid?
123
- => false
124
- >> p.errors
125
- => {:name=>["can't be blank"]}
126
-
127
- >> p = Person.create
128
- => #<Person id: nil, name: nil>
129
- >> p.errors
130
- => {:name=>["can't be blank"]}
131
-
132
- >> p.save
133
- => false
134
-
135
- >> p.save!
136
- => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
137
-
138
- >> Person.create!
139
- => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
140
- </ruby>
141
-
142
- +invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations, returning true if any errors were found in the object, and false otherwise.
143
-
144
- h4(#validations_overview-errors). +errors[]+
145
-
146
- To verify whether or not a particular attribute of an object is valid, you can use +errors[:attribute]+. It returns an array of all the errors for +:attribute+. If there are no errors on the specified attribute, an empty array is returned.
147
-
148
- 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.
149
-
150
- <ruby>
151
- class Person < ActiveRecord::Base
152
- validates :name, :presence => true
153
- end
154
-
155
- >> Person.new.errors[:name].any? # => false
156
- >> Person.create.errors[:name].any? # => true
157
- </ruby>
158
-
159
- 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.
160
-
161
- h3. Validation Helpers
162
-
163
- 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 attribute being validated.
164
-
165
- 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.
166
-
167
- 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.
168
-
169
- h4. +acceptance+
170
-
171
- 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).
172
-
173
- <ruby>
174
- class Person < ActiveRecord::Base
175
- validates :terms_of_service, :acceptance => true
176
- end
177
- </ruby>
178
-
179
- The default error message for this helper is "_must be accepted_".
180
-
181
- It can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1" and can be easily changed.
182
-
183
- <ruby>
184
- class Person < ActiveRecord::Base
185
- validates :terms_of_service, :acceptance => { :accept => 'yes' }
186
- end
187
- </ruby>
188
-
189
- h4. +validates_associated+
190
-
191
- 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.
192
-
193
- <ruby>
194
- class Library < ActiveRecord::Base
195
- has_many :books
196
- validates_associated :books
197
- end
198
- </ruby>
199
-
200
- This validation will work with all of the association types.
201
-
202
- CAUTION: Don't use +validates_associated+ on both ends of your associations. They would call each other in an infinite loop.
203
-
204
- 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.
205
-
206
- h4. +confirmation+
207
-
208
- 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.
209
-
210
- <ruby>
211
- class Person < ActiveRecord::Base
212
- validates :email, :confirmation => true
213
- end
214
- </ruby>
215
-
216
- In your view template you could use something like
217
-
218
- <erb>
219
- <%= text_field :person, :email %>
220
- <%= text_field :person, :email_confirmation %>
221
- </erb>
222
-
223
- 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 +presence+ later on this guide):
224
-
225
- <ruby>
226
- class Person < ActiveRecord::Base
227
- validates :email, :confirmation => true
228
- validates :email_confirmation, :presence => true
229
- end
230
- </ruby>
231
-
232
- The default error message for this helper is "_doesn't match confirmation_".
233
-
234
- h4. +exclusion+
235
-
236
- This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
237
-
238
- <ruby>
239
- class Account < ActiveRecord::Base
240
- validates :subdomain, :exclusion => { :in => %w(www us ca jp),
241
- :message => "Subdomain %{value} is reserved." }
242
- end
243
- </ruby>
244
-
245
- The +exclusion+ 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.
246
-
247
- The default error message is "_is reserved_".
248
-
249
- h4. +format+
250
-
251
- This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the +:with+ option.
252
-
253
- <ruby>
254
- class Product < ActiveRecord::Base
255
- validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/,
256
- :message => "Only letters allowed" }
257
- end
258
- </ruby>
259
-
260
- The default error message is "_is invalid_".
261
-
262
- h4. +inclusion+
263
-
264
- This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
265
-
266
- <ruby>
267
- class Coffee < ActiveRecord::Base
268
- validates :size, :inclusion => { :in => %w(small medium large),
269
- :message => "%{value} is not a valid size" }
270
- end
271
- </ruby>
272
-
273
- The +inclusion+ 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.
274
-
275
- The default error message for this helper is "_is not included in the list_".
276
-
277
- h4. +length+
278
-
279
- This helper validates the length of the attributes' values. It provides a variety of options, so you can specify length constraints in different ways:
280
-
281
- <ruby>
282
- class Person < ActiveRecord::Base
283
- validates :name, :length => { :minimum => 2 }
284
- validates :bio, :length => { :maximum => 500 }
285
- validates :password, :length => { :in => 6..20 }
286
- validates :registration_number, :length => { :is => 6 }
287
- end
288
- </ruby>
289
-
290
- The possible length constraint options are:
291
-
292
- * +:minimum+ - The attribute cannot have less than the specified length.
293
- * +:maximum+ - The attribute cannot have more than the specified length.
294
- * +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a range.
295
- * +:is+ - The attribute length must be equal to the given value.
296
-
297
- 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.
298
-
299
- <ruby>
300
- class Person < ActiveRecord::Base
301
- validates :bio, :length => { :maximum => 1000,
302
- :too_long => "%{count} characters is the maximum allowed" }
303
- end
304
- </ruby>
305
-
306
- This helper counts characters by default, but you can split the value in a different way using the +:tokenizer+ option:
307
-
308
- <ruby>
309
- class Essay < ActiveRecord::Base
310
- validates :content, :length => {
311
- :minimum => 300,
312
- :maximum => 400,
313
- :tokenizer => lambda { |str| str.scan(/\w+/) },
314
- :too_short => "must have at least %{count} words",
315
- :too_long => "must have at most %{count} words"
316
- }
317
- end
318
- </ruby>
319
-
320
- Note that the default error messages are plural (e.g., "is too short (minimum is %{count} characters)"). For this reason, when +:minimum+ is 1 you should provide a personalized message or use +validates_presence_of+ instead. When +:in+ or +:within+ have a lower limit of 1, you should either provide a personalized message or call +presence+ prior to +length+.
321
-
322
- The +size+ helper is an alias for +length+.
323
-
324
- h4. +numericality+
325
-
326
- 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.
327
-
328
- If you set +:only_integer+ to +true+, then it will use the
329
-
330
- <ruby>
331
- /\A[<plus>-]?\d<plus>\Z/
332
- </ruby>
333
-
334
- regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using +Float+.
335
-
336
- WARNING. Note that the regular expression above allows a trailing newline character.
337
-
338
- <ruby>
339
- class Player < ActiveRecord::Base
340
- validates :points, :numericality => true
341
- validates :games_played, :numericality => { :only_integer => true }
342
- end
343
- </ruby>
344
-
345
- Besides +:only_integer+, this helper also accepts the following options to add constraints to acceptable values:
346
-
347
- * +: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}_".
348
- * +: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}_".
349
- * +: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}_".
350
- * +: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}_".
351
- * +: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 than or equal to %{count}_".
352
- * +:odd+ - Specifies the value must be an odd number if set to true. The default error message for this option is "_must be odd_".
353
- * +:even+ - Specifies the value must be an even number if set to true. The default error message for this option is "_must be even_".
354
-
355
- The default error message is "_is not a number_".
356
-
357
- h4. +presence+
358
-
359
- 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.
360
-
361
- <ruby>
362
- class Person < ActiveRecord::Base
363
- validates :name, :login, :email, :presence => true
364
- end
365
- </ruby>
366
-
367
- 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.
368
-
369
- <ruby>
370
- class LineItem < ActiveRecord::Base
371
- belongs_to :order
372
- validates :order_id, :presence => true
373
- end
374
- </ruby>
375
-
376
- Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use <tt>validates :field_name, :inclusion => { :in => [true, false] }</tt>.
377
-
378
- The default error message is "_can't be empty_".
379
-
380
- h4. +uniqueness+
381
-
382
- This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index in your database.
383
-
384
- <ruby>
385
- class Account < ActiveRecord::Base
386
- validates :email, :uniqueness => true
387
- end
388
- </ruby>
389
-
390
- The validation happens by performing an SQL query into the model's table, searching for an existing record with the same value in that attribute.
391
-
392
- There is a +:scope+ option that you can use to specify other attributes that are used to limit the uniqueness check:
393
-
394
- <ruby>
395
- class Holiday < ActiveRecord::Base
396
- validates :name, :uniqueness => { :scope => :year,
397
- :message => "should happen once per year" }
398
- end
399
- </ruby>
400
-
401
- 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.
402
-
403
- <ruby>
404
- class Person < ActiveRecord::Base
405
- validates :name, :uniqueness => { :case_sensitive => false }
406
- end
407
- </ruby>
408
-
409
- WARNING. Note that some databases are configured to perform case-insensitive searches anyway.
410
-
411
- The default error message is "_has already been taken_".
412
-
413
- h4. +validates_with+
414
-
415
- This helper passes the record to a separate class for validation.
416
-
417
- <ruby>
418
- class Person < ActiveRecord::Base
419
- validates_with GoodnessValidator
420
- end
421
-
422
- class GoodnessValidator < ActiveModel::Validator
423
- def validate(record)
424
- if record.first_name == "Evil"
425
- record.errors[:base] << "This person is evil"
426
- end
427
- end
428
- end
429
- </ruby>
430
-
431
- NOTE: Errors added to +record.errors[:base]+ relate to the state of the record as a whole, and not to a specific attribute.
432
-
433
- 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.
434
-
435
- To implement the validate method, you must have a +record+ parameter defined, which is the record to be validated.
436
-
437
- 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+:
438
-
439
- <ruby>
440
- class Person < ActiveRecord::Base
441
- validates_with GoodnessValidator, :fields => [:first_name, :last_name]
442
- end
443
-
444
- class GoodnessValidator < ActiveModel::Validator
445
- def validate(record)
446
- if options[:fields].any?{|field| record.send(field) == "Evil" }
447
- record.errors[:base] << "This person is evil"
448
- end
449
- end
450
- end
451
- </ruby>
452
-
453
- h4. +validates_each+
454
-
455
- 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.
456
-
457
- <ruby>
458
- class Person < ActiveRecord::Base
459
- validates_each :name, :surname do |record, attr, value|
460
- record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
461
- end
462
- end
463
- </ruby>
464
-
465
- The block receives the record, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you should add an error message to the model, therefore making it invalid.
466
-
467
- h3. Common Validation Options
468
-
469
- These are common validation options:
470
-
471
- h4. +:allow_nil+
472
-
473
- The +:allow_nil+ option skips the validation when the value being validated is +nil+.
474
-
475
- <ruby>
476
- class Coffee < ActiveRecord::Base
477
- validates :size, :inclusion => { :in => %w(small medium large),
478
- :message => "%{value} is not a valid size" }, :allow_nil => true
479
- end
480
- </ruby>
481
-
482
- TIP: +:allow_nil+ is ignored by the presence validator.
483
-
484
- h4. +:allow_blank+
485
-
486
- 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.
487
-
488
- <ruby>
489
- class Topic < ActiveRecord::Base
490
- validates :title, :length => { :is => 5 }, :allow_blank => true
491
- end
492
-
493
- Topic.create("title" => "").valid? # => true
494
- Topic.create("title" => nil).valid? # => true
495
- </ruby>
496
-
497
- TIP: +:allow_blank+ is ignored by the presence validator.
498
-
499
- h4. +:message+
500
-
501
- 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.
502
-
503
- h4. +:on+
504
-
505
- The +:on+ option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be run on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +: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.
506
-
507
- <ruby>
508
- class Person < ActiveRecord::Base
509
- # it will be possible to update email with a duplicated value
510
- validates :email, :uniqueness => true, :on => :create
511
-
512
- # it will be possible to create the record with a non-numerical age
513
- validates :age, :numericality => true, :on => :update
514
-
515
- # the default (validates on both create and update)
516
- validates :name, :presence => true, :on => :save
517
- end
518
- </ruby>
519
-
520
- h3. Conditional Validation
521
-
522
- 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.
523
-
524
- h4. Using a Symbol with +:if+ and +:unless+
525
-
526
- 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.
527
-
528
- <ruby>
529
- class Order < ActiveRecord::Base
530
- validates :card_number, :presence => true, :if => :paid_with_card?
531
-
532
- def paid_with_card?
533
- payment_type == "card"
534
- end
535
- end
536
- </ruby>
537
-
538
- h4. Using a String with +:if+ and +:unless+
539
-
540
- 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.
541
-
542
- <ruby>
543
- class Person < ActiveRecord::Base
544
- validates :surname, :presence => true, :if => "name.nil?"
545
- end
546
- </ruby>
547
-
548
- h4. Using a Proc with +:if+ and +:unless+
549
-
550
- 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.
551
-
552
- <ruby>
553
- class Account < ActiveRecord::Base
554
- validates :password, :confirmation => true,
555
- :unless => Proc.new { |a| a.password.blank? }
556
- end
557
- </ruby>
558
-
559
- h4. Grouping conditional validations
560
-
561
- Sometimes it is useful to have multiple validations use one condition, it can be easily achieved using +with_options+.
562
-
563
- <ruby>
564
- class User < ActiveRecord::Base
565
- with_options :if => :is_admin? do |admin|
566
- admin.validates :password, :length => { :minimum => 10 }
567
- admin.validates :email, :presence => true
568
- end
569
- end
570
- </ruby>
571
-
572
- All validations inside of +with_options+ block will have automatically passed the condition +:if => :is_admin?+
573
-
574
- h3. Performing Custom Validations
575
-
576
- When the built-in validation helpers are not enough for your needs, you can write your own validators or validation methods as you prefer.
577
-
578
- h4. Custom Validators
579
-
580
- Custom validators are classes that extend <tt>ActiveModel::Validator</tt>. These classes must implement a +validate+ method which takes a record as an argument and performs the validation on it. The custom validator is called using the +validates_with+ method.
581
-
582
- <ruby>
583
- class MyValidator < ActiveModel::Validator
584
- def validate(record)
585
- unless record.name.starts_with? 'X'
586
- record.errors[:name] << 'Need a name starting with X please!'
587
- end
588
- end
589
- end
590
-
591
- class Person
592
- include ActiveModel::Validations
593
- validates_with MyValidator
594
- end
595
- </ruby>
596
-
597
- The easiest way to add custom validators for validating individual attributes is with the convenient <tt>ActiveModel::EachValidator</tt>. In this case, the custom validator class must implement a +validate_each+ method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance.
598
-
599
- <ruby>
600
- class EmailValidator < ActiveModel::EachValidator
601
- def validate_each(record, attribute, value)
602
- unless value =~ /\A([^@\s]<plus>)@((?:[-a-z0-9]<plus>\.)+[a-z]{2,})\z/i
603
- record.errors[attribute] << (options[:message] || "is not an email")
604
- end
605
- end
606
- end
607
-
608
- class Person < ActiveRecord::Base
609
- validates :email, :presence => true, :email => true
610
- end
611
- </ruby>
612
-
613
- As shown in the example, you can also combine standard validations with your own custom validators.
614
-
615
- h4. Custom Methods
616
-
617
- You can also 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 the +validate+ class method, passing in the symbols for the validation methods' names.
618
-
619
- 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.
620
-
621
- <ruby>
622
- class Invoice < ActiveRecord::Base
623
- validate :expiration_date_cannot_be_in_the_past,
624
- :discount_cannot_be_greater_than_total_value
625
-
626
- def expiration_date_cannot_be_in_the_past
627
- if !expiration_date.blank? and expiration_date < Date.today
628
- errors.add(:expiration_date, "can't be in the past")
629
- end
630
- end
631
-
632
- def discount_cannot_be_greater_than_total_value
633
- if discount > total_value
634
- errors.add(:discount, "can't be greater than total value")
635
- end
636
- end
637
- end
638
- </ruby>
639
-
640
- By default such validations will run every time you call +valid?+. It is also possible to control when to run these custom validations by giving an +:on+ option to the +validate+ method, with either: +:create+ or +:update+.
641
-
642
- <ruby>
643
- class Invoice < ActiveRecord::Base
644
- validate :active_customer, :on => :create
645
-
646
- def active_customer
647
- errors.add(:customer_id, "is not active") unless customer.active?
648
- end
649
- end
650
- </ruby>
651
-
652
- You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices:
653
-
654
- <ruby>
655
- ActiveRecord::Base.class_eval do
656
- def self.validates_as_choice(attr_name, n, options={})
657
- validates attr_name, :inclusion => { { :in => 1..n }.merge!(options) }
658
- end
659
- end
660
- </ruby>
661
-
662
- 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:
663
-
664
- <ruby>
665
- class Movie < ActiveRecord::Base
666
- validates_as_choice :rating, 5
667
- end
668
- </ruby>
669
-
670
- h3. Working with Validation Errors
671
-
672
- 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.
673
-
674
- 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.
675
-
676
- h4(#working_with_validation_errors-errors). +errors+
677
-
678
- Returns an instance of the class +ActiveModel::Errors+ (which behaves like an ordered hash) containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
679
-
680
- <ruby>
681
- class Person < ActiveRecord::Base
682
- validates :name, :presence => true, :length => { :minimum => 3 }
683
- end
684
-
685
- person = Person.new
686
- person.valid? # => false
687
- person.errors
688
- # => {:name => ["can't be blank", "is too short (minimum is 3 characters)"]}
689
-
690
- person = Person.new(:name => "John Doe")
691
- person.valid? # => true
692
- person.errors # => []
693
- </ruby>
694
-
695
- h4(#working_with_validation_errors-errors-2). +errors[]+
696
-
697
- +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.
698
-
699
- <ruby>
700
- class Person < ActiveRecord::Base
701
- validates :name, :presence => true, :length => { :minimum => 3 }
702
- end
703
-
704
- person = Person.new(:name => "John Doe")
705
- person.valid? # => true
706
- person.errors[:name] # => []
707
-
708
- person = Person.new(:name => "JD")
709
- person.valid? # => false
710
- person.errors[:name] # => ["is too short (minimum is 3 characters)"]
711
-
712
- person = Person.new
713
- person.valid? # => false
714
- person.errors[:name]
715
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
716
- </ruby>
717
-
718
- h4. +errors.add+
719
-
720
- 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.
721
-
722
- <ruby>
723
- class Person < ActiveRecord::Base
724
- def a_method_used_for_validation_purposes
725
- errors.add(:name, "cannot contain the characters !@#%*()_-+=")
726
- end
727
- end
728
-
729
- person = Person.create(:name => "!@#")
730
-
731
- person.errors[:name]
732
- # => ["cannot contain the characters !@#%*()_-+="]
733
-
734
- person.errors.full_messages
735
- # => ["Name cannot contain the characters !@#%*()_-+="]
736
- </ruby>
737
-
738
- Another way to do this is using +[]=+ setter
739
-
740
- <ruby>
741
- class Person < ActiveRecord::Base
742
- def a_method_used_for_validation_purposes
743
- errors[:name] = "cannot contain the characters !@#%*()_-+="
744
- end
745
- end
746
-
747
- person = Person.create(:name => "!@#")
748
-
749
- person.errors[:name]
750
- # => ["cannot contain the characters !@#%*()_-+="]
751
-
752
- person.errors.to_a
753
- # => ["Name cannot contain the characters !@#%*()_-+="]
754
- </ruby>
755
-
756
- h4. +errors[:base]+
757
-
758
- 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.
759
-
760
- <ruby>
761
- class Person < ActiveRecord::Base
762
- def a_method_used_for_validation_purposes
763
- errors[:base] << "This person is invalid because ..."
764
- end
765
- end
766
- </ruby>
767
-
768
- h4. +errors.clear+
769
-
770
- 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.
771
-
772
- <ruby>
773
- class Person < ActiveRecord::Base
774
- validates :name, :presence => true, :length => { :minimum => 3 }
775
- end
776
-
777
- person = Person.new
778
- person.valid? # => false
779
- person.errors[:name]
780
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
781
-
782
- person.errors.clear
783
- person.errors.empty? # => true
784
-
785
- p.save # => false
786
-
787
- p.errors[:name]
788
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
789
- </ruby>
790
-
791
- h4. +errors.size+
792
-
793
- The +size+ method returns the total number of error messages for the object.
794
-
795
- <ruby>
796
- class Person < ActiveRecord::Base
797
- validates :name, :presence => true, :length => { :minimum => 3 }
798
- end
799
-
800
- person = Person.new
801
- person.valid? # => false
802
- person.errors.size # => 2
803
-
804
- person = Person.new(:name => "Andrea", :email => "andrea@example.com")
805
- person.valid? # => true
806
- person.errors.size # => 0
807
- </ruby>
808
-
809
- h3. Displaying Validation Errors in the View
810
-
811
- "DynamicForm":https://github.com/joelmoss/dynamic_form provides helpers to display the error messages of your models in your view templates.
812
-
813
- You can install it as a gem by adding this line to your Gemfile:
814
-
815
- <ruby>
816
- gem "dynamic_form"
817
- </ruby>
818
-
819
- Now you will have access to the two helper methods +error_messages+ and +error_messages_for+ in your view templates.
820
-
821
- h4. +error_messages+ and +error_messages_for+
822
-
823
- 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.
824
-
825
- <ruby>
826
- class Product < ActiveRecord::Base
827
- validates :description, :value, :presence => true
828
- validates :value, :numericality => true, :allow_nil => true
829
- end
830
- </ruby>
831
-
832
- <erb>
833
- <%= form_for(@product) do |f| %>
834
- <%= f.error_messages %>
835
- <p>
836
- <%= f.label :description %><br />
837
- <%= f.text_field :description %>
838
- </p>
839
- <p>
840
- <%= f.label :value %><br />
841
- <%= f.text_field :value %>
842
- </p>
843
- <p>
844
- <%= f.submit "Create" %>
845
- </p>
846
- <% end %>
847
- </erb>
848
-
849
- If you submit the form with empty fields, the result will be similar to the one shown below:
850
-
851
- !images/error_messages.png(Error messages)!
852
-
853
- NOTE: The appearance of the generated HTML will be different from the one shown, unless you have used scaffolding. See "Customizing the Error Messages CSS":#customizing-error-messages-css.
854
-
855
- You can also use the +error_messages_for+ helper to display the error messages of a model assigned to a view template. It is very similar to the previous example and will achieve exactly the same result.
856
-
857
- <erb>
858
- <%= error_messages_for :product %>
859
- </erb>
860
-
861
- 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.
862
-
863
- Both the +form.error_messages+ and the +error_messages_for+ helpers accept options that let you customize the +div+ element that holds the messages, change the header text, change the message below the header, and specify the tag used for the header element. For example,
864
-
865
- <erb>
866
- <%= f.error_messages :header_message => "Invalid product!",
867
- :message => "You'll need to fix the following fields:",
868
- :header_tag => :h3 %>
869
- </erb>
870
-
871
- results in:
872
-
873
- !images/customized_error_messages.png(Customized error messages)!
874
-
875
- If you pass +nil+ in any of these options, the corresponding section of the +div+ will be discarded.
876
-
877
- h4(#customizing-error-messages-css). Customizing the Error Messages CSS
878
-
879
- The selectors used to customize the style of error messages are:
880
-
881
- * +.field_with_errors+ - Style for the form fields and labels with errors.
882
- * +#error_explanation+ - Style for the +div+ element with the error messages.
883
- * +#error_explanation h2+ - Style for the header of the +div+ element.
884
- * +#error_explanation p+ - Style for the paragraph holding the message that appears right below the header of the +div+ element.
885
- * +#error_explanation ul li+ - Style for the list items with individual error messages.
886
-
887
- If scaffolding was used, file +app/assets/stylesheets/scaffolds.css.scss+ will have been generated automatically. This file defines the red-based styles you saw in the examples above.
888
-
889
- The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers.
890
-
891
- h4. Customizing the Error Messages HTML
892
-
893
- By default, form fields with errors are displayed enclosed by a +div+ element with the +field_with_errors+ CSS class. However, it's possible to override that.
894
-
895
- The way form fields with errors are treated is defined by +ActionView::Base.field_error_proc+. This is a +Proc+ that receives two parameters:
896
-
897
- * A string with the HTML tag
898
- * An instance of +ActionView::Helpers::InstanceTag+.
899
-
900
- Below is a simple example where we change the Rails behavior to always display the error messages in front of each of the form fields in error. The error messages will be enclosed by a +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.
901
-
902
- <ruby>
903
- ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
904
- if html_tag =~ /\<label/
905
- html_tag
906
- else
907
- errors = Array(instance.error_message).join(',')
908
- %(#{html_tag}<span class="validation-error">&nbsp;#{errors}</span>).html_safe
909
- end
910
- end
911
- </ruby>
912
-
913
- The result looks like the following:
914
-
915
- !images/validation_error_messages.png(Validation error messages)!
916
-
917
- h3. Callbacks Overview
918
-
919
- Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
920
-
921
- h4. Callback Registration
922
-
923
- In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks:
924
-
925
- <ruby>
926
- class User < ActiveRecord::Base
927
- validates :login, :email, :presence => true
928
-
929
- before_validation :ensure_login_has_a_value
930
-
931
- protected
932
- def ensure_login_has_a_value
933
- if login.nil?
934
- self.login = email unless email.blank?
935
- end
936
- end
937
- end
938
- </ruby>
939
-
940
- The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in a single line:
941
-
942
- <ruby>
943
- class User < ActiveRecord::Base
944
- validates :login, :email, :presence => true
945
-
946
- before_create do |user|
947
- user.name = user.login.capitalize if user.name.blank?
948
- end
949
- end
950
- </ruby>
951
-
952
- It is considered good practice to declare callback methods as protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.
953
-
954
- h3. Available Callbacks
955
-
956
- 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:
957
-
958
- h4. Creating an Object
959
-
960
- * +before_validation+
961
- * +after_validation+
962
- * +before_save+
963
- * +around_save+
964
- * +before_create+
965
- * +around_create+
966
- * +after_create+
967
- * +after_save+
968
-
969
- h4. Updating an Object
970
-
971
- * +before_validation+
972
- * +after_validation+
973
- * +before_save+
974
- * +around_save+
975
- * +before_update+
976
- * +around_update+
977
- * +after_update+
978
- * +after_save+
979
-
980
- h4. Destroying an Object
981
-
982
- * +before_destroy+
983
- * +around_destroy+
984
- * +after_destroy+
985
-
986
- 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.
987
-
988
- h4. +after_initialize+ and +after_find+
989
-
990
- 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.
991
-
992
- 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.
993
-
994
- The +after_initialize+ and +after_find+ callbacks have no +before_*+ counterparts, but they can be registered just like the other Active Record callbacks.
995
-
996
- <ruby>
997
- class User < ActiveRecord::Base
998
- after_initialize do |user|
999
- puts "You have initialized an object!"
1000
- end
1001
-
1002
- after_find do |user|
1003
- puts "You have found an object!"
1004
- end
1005
- end
1006
-
1007
- >> User.new
1008
- You have initialized an object!
1009
- => #<User id: nil>
1010
-
1011
- >> User.first
1012
- You have found an object!
1013
- You have initialized an object!
1014
- => #<User id: 1>
1015
- </ruby>
1016
-
1017
- h3. Running Callbacks
1018
-
1019
- The following methods trigger callbacks:
1020
-
1021
- * +create+
1022
- * +create!+
1023
- * +decrement!+
1024
- * +destroy+
1025
- * +destroy_all+
1026
- * +increment!+
1027
- * +save+
1028
- * +save!+
1029
- * +save(:validate => false)+
1030
- * +toggle!+
1031
- * +update+
1032
- * +update_attribute+
1033
- * +update_attributes+
1034
- * +update_attributes!+
1035
- * +valid?+
1036
-
1037
- Additionally, the +after_find+ callback is triggered by the following finder methods:
1038
-
1039
- * +all+
1040
- * +first+
1041
- * +find+
1042
- * +find_all_by_<em>attribute</em>+
1043
- * +find_by_<em>attribute</em>+
1044
- * +find_by_<em>attribute</em>!+
1045
- * +last+
1046
-
1047
- The +after_initialize+ callback is triggered every time a new object of the class is initialized.
1048
-
1049
- h3. Skipping Callbacks
1050
-
1051
- Just as with validations, it is also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
1052
-
1053
- * +decrement+
1054
- * +decrement_counter+
1055
- * +delete+
1056
- * +delete_all+
1057
- * +find_by_sql+
1058
- * +increment+
1059
- * +increment_counter+
1060
- * +toggle+
1061
- * +touch+
1062
- * +update_column+
1063
- * +update_all+
1064
- * +update_counters+
1065
-
1066
- h3. Halting Execution
1067
-
1068
- 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.
1069
-
1070
- The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly +false+ or raises an exception, the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception.
1071
-
1072
- WARNING. Raising an arbitrary exception may break code that expects +save+ and its 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.
1073
-
1074
- h3. Relational Callbacks
1075
-
1076
- Callbacks work through model relationships, and can even be defined by them. Suppose an example where a user has many posts. A user's posts should be destroyed if the user is destroyed. Let's add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model:
1077
-
1078
- <ruby>
1079
- class User < ActiveRecord::Base
1080
- has_many :posts, :dependent => :destroy
1081
- end
1082
-
1083
- class Post < ActiveRecord::Base
1084
- after_destroy :log_destroy_action
1085
-
1086
- def log_destroy_action
1087
- puts 'Post destroyed'
1088
- end
1089
- end
1090
-
1091
- >> user = User.first
1092
- => #<User id: 1>
1093
- >> user.posts.create!
1094
- => #<Post id: 1, user_id: 1>
1095
- >> user.destroy
1096
- Post destroyed
1097
- => #<User id: 1>
1098
- </ruby>
1099
-
1100
- h3. Conditional Callbacks
1101
-
1102
- As with validations, we can also make the calling of a callback method conditional on the satisfaction of a given predicate. We can do this using the +: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 under which conditions the callback *should* be called. If you want to specify the conditions under which the callback *should not* be called, then you may use the +:unless+ option.
1103
-
1104
- h4. Using +:if+ and +:unless+ with a +Symbol+
1105
-
1106
- You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the +:if+ option, the callback won't be executed if the predicate method returns false; when using the +:unless+ option, the callback won't be executed if the predicate method returns true. This is the most common option. Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed.
1107
-
1108
- <ruby>
1109
- class Order < ActiveRecord::Base
1110
- before_save :normalize_card_number, :if => :paid_with_card?
1111
- end
1112
- </ruby>
1113
-
1114
- h4. Using +:if+ and +:unless+ with a String
1115
-
1116
- You can also use a string that will be evaluated using +eval+ and hence needs to contain valid Ruby code. You should use this option only when the string represents a really short condition:
1117
-
1118
- <ruby>
1119
- class Order < ActiveRecord::Base
1120
- before_save :normalize_card_number, :if => "paid_with_card?"
1121
- end
1122
- </ruby>
1123
-
1124
- h4. Using +:if+ and +:unless+ with a +Proc+
1125
-
1126
- Finally, it is possible to associate +:if+ and +:unless+ with a +Proc+ object. This option is best suited when writing short validation methods, usually one-liners:
1127
-
1128
- <ruby>
1129
- class Order < ActiveRecord::Base
1130
- before_save :normalize_card_number,
1131
- :if => Proc.new { |order| order.paid_with_card? }
1132
- end
1133
- </ruby>
1134
-
1135
- h4. Multiple Conditions for Callbacks
1136
-
1137
- When writing conditional callbacks, it is possible to mix both +:if+ and +:unless+ in the same callback declaration:
1138
-
1139
- <ruby>
1140
- class Comment < ActiveRecord::Base
1141
- after_create :send_email_to_author, :if => :author_wants_emails?,
1142
- :unless => Proc.new { |comment| comment.post.ignore_comments? }
1143
- end
1144
- </ruby>
1145
-
1146
- h3. Callback Classes
1147
-
1148
- 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.
1149
-
1150
- Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model:
1151
-
1152
- <ruby>
1153
- class PictureFileCallbacks
1154
- def after_destroy(picture_file)
1155
- if File.exists?(picture_file.filepath)
1156
- File.delete(picture_file.filepath)
1157
- end
1158
- end
1159
- end
1160
- </ruby>
1161
-
1162
- When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:
1163
-
1164
- <ruby>
1165
- class PictureFile < ActiveRecord::Base
1166
- after_destroy PictureFileCallbacks.new
1167
- end
1168
- </ruby>
1169
-
1170
- Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of the instantiated object. Often, however, it will make more sense to declare the callbacks as class methods:
1171
-
1172
- <ruby>
1173
- class PictureFileCallbacks
1174
- def self.after_destroy(picture_file)
1175
- if File.exists?(picture_file.filepath)
1176
- File.delete(picture_file.filepath)
1177
- end
1178
- end
1179
- end
1180
- </ruby>
1181
-
1182
- If the callback method is declared this way, it won't be necessary to instantiate a +PictureFileCallbacks+ object.
1183
-
1184
- <ruby>
1185
- class PictureFile < ActiveRecord::Base
1186
- after_destroy PictureFileCallbacks
1187
- end
1188
- </ruby>
1189
-
1190
- You can declare as many callbacks as you want inside your callback classes.
1191
-
1192
- h3. Observers
1193
-
1194
- Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add the same functionality without changing the code of the model. For example, it could be argued that a +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.
1195
-
1196
- h4. Creating Observers
1197
-
1198
- 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 should create an observer to contain the code implementing this functionality.
1199
-
1200
- <shell>
1201
- $ rails generate observer User
1202
- </shell>
1203
-
1204
- generates +app/models/user_observer.rb+ containing the observer class +UserObserver+:
1205
-
1206
- <ruby>
1207
- class UserObserver < ActiveRecord::Observer
1208
- end
1209
- </ruby>
1210
-
1211
- You may now add methods to be called at the desired occasions:
1212
-
1213
- <ruby>
1214
- class UserObserver < ActiveRecord::Observer
1215
- def after_create(model)
1216
- # code to send confirmation email...
1217
- end
1218
- end
1219
- </ruby>
1220
-
1221
- As with callback classes, the observer's methods receive the observed model as a parameter.
1222
-
1223
- h4. Registering Observers
1224
-
1225
- Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/application.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/application.rb+ this way:
1226
-
1227
- <ruby>
1228
- # Activate observers that should always be running.
1229
- config.active_record.observers = :user_observer
1230
- </ruby>
1231
-
1232
- As usual, settings in +config/environments+ take precedence over those in +config/application.rb+. So, if you prefer that an observer doesn't run in all environments, you can simply register it in a specific environment instead.
1233
-
1234
- h4. Sharing Observers
1235
-
1236
- By default, Rails will simply strip "Observer" from an observer's name to find the model it should observe. However, observers can also be used to add behavior to more than one model, and thus it is possible to explicitly specify the models that our observer should observe:
1237
-
1238
- <ruby>
1239
- class MailerObserver < ActiveRecord::Observer
1240
- observe :registration, :user
1241
-
1242
- def after_create(model)
1243
- # code to send confirmation email...
1244
- end
1245
- end
1246
- </ruby>
1247
-
1248
- In this example, the +after_create+ method will be called whenever a +Registration+ or +User+ is created. Note that this new +MailerObserver+ would also need to be registered in +config/application.rb+ in order to take effect:
1249
-
1250
- <ruby>
1251
- # Activate observers that should always be running.
1252
- config.active_record.observers = :mailer_observer
1253
- </ruby>
1254
-
1255
- h3. Transaction Callbacks
1256
-
1257
- There are two additional callbacks that are triggered by the completion of a database transaction: +after_commit+ and +after_rollback+. These callbacks are very similar to the +after_save+ callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction.
1258
-
1259
- Consider, for example, the previous example where the +PictureFile+ model needs to delete a file after the corresponding record is destroyed. If anything raises an exception after the +after_destroy+ callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that +picture_file_2+ in the code below is not valid and the +save!+ method raises an error.
1260
-
1261
- <ruby>
1262
- PictureFile.transaction do
1263
- picture_file_1.destroy
1264
- picture_file_2.save!
1265
- end
1266
- </ruby>
1267
-
1268
- By using the +after_commit+ callback we can account for this case.
1269
-
1270
- <ruby>
1271
- class PictureFile < ActiveRecord::Base
1272
- attr_accessor :delete_file
1273
-
1274
- after_destroy do |picture_file|
1275
- picture_file.delete_file = picture_file.filepath
1276
- end
1277
-
1278
- after_commit do |picture_file|
1279
- if picture_file.delete_file && File.exist?(picture_file.delete_file)
1280
- File.delete(picture_file.delete_file)
1281
- picture_file.delete_file = nil
1282
- end
1283
- end
1284
- end
1285
- </ruby>
1286
-
1287
- The +after_commit+ and +after_rollback+ callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback.