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,205 +0,0 @@
1
- h2. Active Model Basics
2
-
3
- This guide should provide you with all you need to get started using model classes. Active Model allow for Action Pack helpers to interact with non-ActiveRecord models. Active Model also helps building custom ORMs for use outside of the Rails framework.
4
-
5
- endprologue.
6
-
7
- WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
8
-
9
- h3. Introduction
10
-
11
- Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below -
12
-
13
- h4. AttributeMethods
14
-
15
- AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes, which methods on the object will use them.
16
-
17
- <ruby>
18
- class Person
19
- include ActiveModel::AttributeMethods
20
-
21
- attribute_method_prefix 'reset_'
22
- attribute_method_suffix '_highest?'
23
- define_attribute_methods ['age']
24
-
25
- attr_accessor :age
26
-
27
- private
28
- def reset_attribute(attribute)
29
- send("#{attribute}=", 0)
30
- end
31
-
32
- def attribute_highest?(attribute)
33
- send(attribute) > 100 ? true : false
34
- end
35
-
36
- end
37
-
38
- person = Person.new
39
- person.age = 110
40
- person.age_highest? # true
41
- person.reset_age # 0
42
- person.age_highest? # false
43
-
44
- </ruby>
45
-
46
- h4. Callbacks
47
-
48
- Callbacks gives Active Record style callbacks. This provides the ability to define the callbacks and those will run at appropriate time. After defining a callbacks you can wrap with before, after and around custom methods.
49
-
50
- <ruby>
51
- class Person
52
- extend ActiveModel::Callbacks
53
-
54
- define_model_callbacks :update
55
-
56
- before_update :reset_me
57
-
58
- def update
59
- _run_update_callbacks do
60
- # This will call when we are trying to call update on object.
61
- end
62
- end
63
-
64
- def reset_me
65
- # This method will call when you are calling update on object as a before_update callback as defined.
66
- end
67
- end
68
- </ruby>
69
-
70
- h4. Conversion
71
-
72
- If a class defines persisted? and id methods then you can include Conversion module in that class and you can able to call Rails conversion methods to objects of that class.
73
-
74
- <ruby>
75
- class Person
76
- include ActiveModel::Conversion
77
-
78
- def persisted?
79
- false
80
- end
81
-
82
- def id
83
- nil
84
- end
85
- end
86
-
87
- person = Person.new
88
- person.to_model == person #=> true
89
- person.to_key #=> nil
90
- person.to_param #=> nil
91
- </ruby>
92
-
93
- h4. Dirty
94
-
95
- An object becomes dirty when an object is gone through one or more changes to its attributes and not yet saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Lets consider a Person class with attributes first_name and last_name
96
-
97
- <ruby>
98
- require 'rubygems'
99
- require 'active_model'
100
-
101
- class Person
102
- include ActiveModel::Dirty
103
- define_attribute_methods [:first_name, :last_name]
104
-
105
- def first_name
106
- @first_name
107
- end
108
-
109
- def first_name=(value)
110
- first_name_will_change!
111
- @first_name = value
112
- end
113
-
114
- def last_name
115
- @last_name
116
- end
117
-
118
- def last_name=(value)
119
- last_name_will_change!
120
- @last_name = value
121
- end
122
-
123
- def save
124
- @previously_changed = changes
125
- end
126
-
127
- end
128
- </ruby>
129
-
130
- h5. Querying object directly for its list of all changed attributes.
131
-
132
- <ruby>
133
- person = Person.new
134
- person.first_name = "First Name"
135
-
136
- person.first_name #=> "First Name"
137
- person.first_name = "First Name Changed"
138
-
139
- person.changed? #=> true
140
-
141
- #returns an list of fields arry which all has been changed before saved.
142
- person.changed #=> ["first_name"]
143
-
144
- #returns a hash of the fields that have changed with their original values.
145
- person.changed_attributes #=> {"first_name" => "First Name Changed"}
146
-
147
- #returns a hash of changes, with the attribute names as the keys, and the values will be an array of the old and new value for that field.
148
- person.changes #=> {"first_name" => ["First Name","First Name Changed"]}
149
- </ruby>
150
-
151
- h5. Attribute based accessor methods
152
-
153
- Track whether the particular attribute has been changed or not.
154
-
155
- <ruby>
156
- #attr_name_changed?
157
- person.first_name #=> "First Name"
158
-
159
- #assign some other value to first_name attribute
160
- person.first_name = "First Name 1"
161
-
162
- person.first_name_changed? #=> true
163
- </ruby>
164
-
165
- Track what was the previous value of the attribute.
166
-
167
- <ruby>
168
- #attr_name_was accessor
169
- person.first_name_was #=> "First Name"
170
- </ruby>
171
-
172
- Track both previous and current value of the changed attribute. Returns an array if changed else returns nil
173
-
174
- <ruby>
175
- #attr_name_change
176
- person.first_name_change #=> ["First Name", "First Name 1"]
177
- person.last_name_change #=> nil
178
- </ruby>
179
-
180
- h4. Validations
181
-
182
- Validations module adds the ability to class objects to validate them in Active Record style.
183
-
184
- <ruby>
185
- class Person
186
- include ActiveModel::Validations
187
-
188
- attr_accessor :name, :email, :token
189
-
190
- validates :name, :presence => true
191
- validates_format_of :email, :with => /^([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})$/i
192
- validates! :token, :presence => true
193
-
194
- end
195
-
196
- person = Person.new(:token => "2b1f325")
197
- person.valid? #=> false
198
- person.name = 'vishnu'
199
- person.email = 'me'
200
- person.valid? #=> false
201
- person.email = 'me@vishnuatrai.com'
202
- person.valid? #=> true
203
- person.token = nil
204
- person.valid? #=> raises ActiveModel::StrictValidationFailed
205
- </ruby>
@@ -1,218 +0,0 @@
1
- h2. Active Record Basics
2
-
3
- This guide is an introduction to Active Record. After reading this guide we hope that you'll learn:
4
-
5
- * What Object Relational Mapping and Active Record are and how they are used in Rails
6
- * How Active Record fits into the Model-View-Controller paradigm
7
- * How to use Active Record models to manipulate data stored in a relational database
8
- * Active Record schema naming conventions
9
- * The concepts of database migrations, validations and callbacks
10
-
11
- endprologue.
12
-
13
- h3. What is Active Record?
14
-
15
- Active Record is the M in "MVC":getting_started.html#the-mvc-architecture - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
16
-
17
- h4. The Active Record Pattern
18
-
19
- Active Record was described by Martin Fowler in his book _Patterns of Enterprise Application Architecture_. In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic is part of the object will educate users of that object on how to write to and read from the database.
20
-
21
- h4. Object Relational Mapping
22
-
23
- Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.
24
-
25
- h4. Active Record as an ORM Framework
26
-
27
- Active Record gives us several mechanisms, the most important being the ability to:
28
-
29
- * Represent models and their data
30
- * Represent associations between these models
31
- * Represent inheritance hierarchies through related models
32
- * Validate models before they get persisted to the database
33
- * Perform database operations in an object-oriented fashion.
34
-
35
- h3. Convention over Configuration in Active Record
36
-
37
- When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particularly true for ORM frameworks in general. However, if you follow the conventions adopted by Rails, you'll need to write very little configuration (in some case no configuration at all) when creating Active Record models. The idea is that if you configure your applications in the very same way most of the times then this should be the default way. In this cases, explicit configuration would be needed only in those cases where you can't follow the conventions for any reason.
38
-
39
- h4. Naming Conventions
40
-
41
- By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class +Book+, you should have a database table called *books*. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples:
42
-
43
- * Database Table - Plural with underscores separating words (e.g., +book_clubs+)
44
- * Model Class - Singular with the first letter of each word capitalized (e.g., +BookClub+)
45
-
46
- |_.Model / Class |_.Table / Schema |
47
- |+Post+ |+posts+|
48
- |+LineItem+ |+line_items+|
49
- |+Deer+ |+deer+|
50
- |+Mouse+ |+mice+|
51
- |+Person+ |+people+|
52
-
53
-
54
- h4. Schema Conventions
55
-
56
- Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns.
57
-
58
- * *Foreign keys* - These fields should be named following the pattern +singularized_table_name_id+ (e.g., +item_id+, +order_id+). These are the fields that Active Record will look for when you create associations between your models.
59
- * *Primary keys* - By default, Active Record will use an integer column named +id+ as the table's primary key. When using "Rails Migrations":migrations.html to create your tables, this column will be automatically created.
60
-
61
- There are also some optional column names that will create additional features to Active Record instances:
62
-
63
- * +created_at+ - Automatically gets set to the current date and time when the record is first created.
64
- * +created_on+ - Automatically gets set to the current date when the record is first created.
65
- * +updated_at+ - Automatically gets set to the current date and time whenever the record is updated.
66
- * +updated_on+ - Automatically gets set to the current date whenever the record is updated.
67
- * +lock_version+ - Adds "optimistic locking":http://api.rubyonrails.org/classes/ActiveRecord/Locking.html to a model.
68
- * +type+ - Specifies that the model uses "Single Table Inheritance":http://api.rubyonrails.org/classes/ActiveRecord/Base.html
69
- * +(table_name)_count+ - Used to cache the number of belonging objects on associations. For example, a +comments_count+ column in a +Post+ class that has many instances of +Comment+ will cache the number of existent comments for each post.
70
-
71
- NOTE: While these column names are optional, they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, +type+ is a reserved keyword used to designate a table using Single Table Inheritance (STI). If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
72
-
73
- h3. Creating Active Record Models
74
-
75
- It is very easy to create Active Record models. All you have to do is to subclass the +ActiveRecord::Base+ class and you're good to go:
76
-
77
- <ruby>
78
- class Product < ActiveRecord::Base
79
- end
80
- </ruby>
81
-
82
- This will create a +Product+ model, mapped to a +products+ table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. Suppose that the +products+ table was created using an SQL sentence like:
83
-
84
- <sql>
85
- CREATE TABLE products (
86
- id int(11) NOT NULL auto_increment,
87
- name varchar(255),
88
- PRIMARY KEY (id)
89
- );
90
- </sql>
91
-
92
- Following the table schema above, you would be able to write code like the following:
93
-
94
- <ruby>
95
- p = Product.new
96
- p.name = "Some Book"
97
- puts p.name # "Some Book"
98
- </ruby>
99
-
100
- h3. Overriding the Naming Conventions
101
-
102
- What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
103
-
104
- You can use the +ActiveRecord::Base.table_name=+ method to specify the table name that should be used:
105
-
106
- <ruby>
107
- class Product < ActiveRecord::Base
108
- self.table_name = "PRODUCT"
109
- end
110
- </ruby>
111
-
112
- If you do so, you will have to define manually the class name that is hosting the fixtures (class_name.yml) using the +set_fixture_class+ method in your test definition:
113
-
114
- <ruby>
115
- class FunnyJoke < ActiveSupport::TestCase
116
- set_fixture_class :funny_jokes => 'Joke'
117
- fixtures :funny_jokes
118
- ...
119
- end
120
- </ruby>
121
-
122
- It's also possible to override the column that should be used as the table's primary key using the +ActiveRecord::Base.set_primary_key+ method:
123
-
124
- <ruby>
125
- class Product < ActiveRecord::Base
126
- set_primary_key "product_id"
127
- end
128
- </ruby>
129
-
130
- h3. CRUD: Reading and Writing Data
131
-
132
- CRUD is an acronym for the four verbs we use to operate on data: *C*reate, *R*ead, *U*pdate and *D*elete. Active Record automatically creates methods to allow an application to read and manipulate data stored within its tables.
133
-
134
- h4. Create
135
-
136
- Active Record objects can be created from a hash, a block or have their attributes manually set after creation. The +new+ method will return a new object while +create+ will return the object and save it to the database.
137
-
138
- For example, given a model +User+ with attributes of +name+ and +occupation+, the +create+ method call will create and save a new record into the database:
139
-
140
- <ruby>
141
- user = User.create(:name => "David", :occupation => "Code Artist")
142
- </ruby>
143
-
144
- Using the +new+ method, an object can be created without being saved:
145
-
146
- <ruby>
147
- user = User.new
148
- user.name = "David"
149
- user.occupation = "Code Artist"
150
- </ruby>
151
-
152
- A call to +user.save+ will commit the record to the database.
153
-
154
- Finally, if a block is provided, both +create+ and +new+ will yield the new object to that block for initialization:
155
-
156
- <ruby>
157
- user = User.new do |u|
158
- u.name = "David"
159
- u.occupation = "Code Artist"
160
- end
161
- </ruby>
162
-
163
- h4. Read
164
-
165
- Active Record provides a rich API for accessing data within a database. Below are a few examples of different data access methods provided by Active Record.
166
-
167
- <ruby>
168
- # return array with all records
169
- users = User.all
170
- </ruby>
171
-
172
- <ruby>
173
- # return the first record
174
- user = User.first
175
- </ruby>
176
-
177
- <ruby>
178
- # return the first user named David
179
- david = User.find_by_name('David')
180
- </ruby>
181
-
182
- <ruby>
183
- # find all users named David who are Code Artists and sort by created_at in reverse chronological order
184
- users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC')
185
- </ruby>
186
-
187
- You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide.
188
-
189
- h4. Update
190
-
191
- Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database.
192
-
193
- <ruby>
194
- user = User.find_by_name('David')
195
- user.name = 'Dave'
196
- user.save
197
- </ruby>
198
-
199
- h4. Delete
200
-
201
- Likewise, once retrieved an Active Record object can be destroyed which removes it from the database.
202
-
203
- <ruby>
204
- user = User.find_by_name('David')
205
- user.destroy
206
- </ruby>
207
-
208
- h3. Validations
209
-
210
- Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. You can learn more about validations in the "Active Record Validations and Callbacks guide":active_record_validations_callbacks.html#validations-overview.
211
-
212
- h3. Callbacks
213
-
214
- Active Record callbacks allow you to attach code to certain events in the life-cycle of your models. This enables you to add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the "Active Record Validations and Callbacks guide":active_record_validations_callbacks.html#callbacks-overview.
215
-
216
- h3. Migrations
217
-
218
- Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any database that Active Record support using rake. Rails keeps track of which files have been committed to the database and provides rollback features. You can learn more about migrations in the "Active Record Migrations guide":migrations.html
@@ -1,1433 +0,0 @@
1
- h2. Active Record Query Interface
2
-
3
- This guide covers different ways to retrieve data from the database using Active Record. By referring to this guide, you will be able to:
4
-
5
- * Find records using a variety of methods and conditions
6
- * Specify the order, retrieved attributes, grouping, and other properties of the found records
7
- * Use eager loading to reduce the number of database queries needed for data retrieval
8
- * Use dynamic finders methods
9
- * Check for the existence of particular records
10
- * Perform various calculations on Active Record models
11
- * Run EXPLAIN on relations
12
-
13
- endprologue.
14
-
15
- WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in other versions of Rails.
16
-
17
- If you're used to using raw SQL to find database records, then you will generally find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
18
-
19
- Code examples throughout this guide will refer to one or more of the following models:
20
-
21
- TIP: All of the following models use +id+ as the primary key, unless specified otherwise.
22
-
23
- <ruby>
24
- class Client < ActiveRecord::Base
25
- has_one :address
26
- has_many :orders
27
- has_and_belongs_to_many :roles
28
- end
29
- </ruby>
30
-
31
- <ruby>
32
- class Address < ActiveRecord::Base
33
- belongs_to :client
34
- end
35
- </ruby>
36
-
37
- <ruby>
38
- class Order < ActiveRecord::Base
39
- belongs_to :client, :counter_cache => true
40
- end
41
- </ruby>
42
-
43
- <ruby>
44
- class Role < ActiveRecord::Base
45
- has_and_belongs_to_many :clients
46
- end
47
- </ruby>
48
-
49
- Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.
50
-
51
- h3. Retrieving Objects from the Database
52
-
53
- To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
54
-
55
- The methods are:
56
- * +where+
57
- * +select+
58
- * +group+
59
- * +order+
60
- * +reorder+
61
- * +reverse_order+
62
- * +limit+
63
- * +offset+
64
- * +joins+
65
- * +includes+
66
- * +lock+
67
- * +readonly+
68
- * +from+
69
- * +having+
70
-
71
- All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>.
72
-
73
- The primary operation of <tt>Model.find(options)</tt> can be summarized as:
74
-
75
- * Convert the supplied options to an equivalent SQL query.
76
- * Fire the SQL query and retrieve the corresponding results from the database.
77
- * Instantiate the equivalent Ruby object of the appropriate model for every resulting row.
78
- * Run +after_find+ callbacks, if any.
79
-
80
- h4. Retrieving a Single Object
81
-
82
- Active Record provides five different ways of retrieving a single object.
83
-
84
- h5. Using a Primary Key
85
-
86
- Using <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example:
87
-
88
- <ruby>
89
- # Find the client with primary key (id) 10.
90
- client = Client.find(10)
91
- # => #<Client id: 10, first_name: "Ryan">
92
- </ruby>
93
-
94
- The SQL equivalent of the above is:
95
-
96
- <sql>
97
- SELECT * FROM clients WHERE (clients.id = 10) LIMIT 1
98
- </sql>
99
-
100
- <tt>Model.find(primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception if no matching record is found.
101
-
102
- h5. +first+
103
-
104
- <tt>Model.first</tt> finds the first record matched by the supplied options, if any. For example:
105
-
106
- <ruby>
107
- client = Client.first
108
- # => #<Client id: 1, first_name: "Lifo">
109
- </ruby>
110
-
111
- The SQL equivalent of the above is:
112
-
113
- <sql>
114
- SELECT * FROM clients LIMIT 1
115
- </sql>
116
-
117
- <tt>Model.first</tt> returns +nil+ if no matching record is found. No exception will be raised.
118
-
119
- h5. +last+
120
-
121
- <tt>Model.last</tt> finds the last record matched by the supplied options. For example:
122
-
123
- <ruby>
124
- client = Client.last
125
- # => #<Client id: 221, first_name: "Russel">
126
- </ruby>
127
-
128
- The SQL equivalent of the above is:
129
-
130
- <sql>
131
- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
132
- </sql>
133
-
134
- <tt>Model.last</tt> returns +nil+ if no matching record is found. No exception will be raised.
135
-
136
- h5(#first_1). +first!+
137
-
138
- <tt>Model.first!</tt> finds the first record. For example:
139
-
140
- <ruby>
141
- client = Client.first!
142
- # => #<Client id: 1, first_name: "Lifo">
143
- </ruby>
144
-
145
- The SQL equivalent of the above is:
146
-
147
- <sql>
148
- SELECT * FROM clients LIMIT 1
149
- </sql>
150
-
151
- <tt>Model.first!</tt> raises +RecordNotFound+ if no matching record is found.
152
-
153
- h5(#last_1). +last!+
154
-
155
- <tt>Model.last!</tt> finds the last record. For example:
156
-
157
- <ruby>
158
- client = Client.last!
159
- # => #<Client id: 221, first_name: "Russel">
160
- </ruby>
161
-
162
- The SQL equivalent of the above is:
163
-
164
- <sql>
165
- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
166
- </sql>
167
-
168
- <tt>Model.last!</tt> raises +RecordNotFound+ if no matching record is found.
169
-
170
- h4. Retrieving Multiple Objects
171
-
172
- h5. Using Multiple Primary Keys
173
-
174
- <tt>Model.find(array_of_primary_key)</tt> accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example:
175
-
176
- <ruby>
177
- # Find the clients with primary keys 1 and 10.
178
- client = Client.find([1, 10]) # Or even Client.find(1, 10)
179
- # => [#<Client id: 1, first_name: "Lifo">, #<Client id: 10, first_name: "Ryan">]
180
- </ruby>
181
-
182
- The SQL equivalent of the above is:
183
-
184
- <sql>
185
- SELECT * FROM clients WHERE (clients.id IN (1,10))
186
- </sql>
187
-
188
- WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
189
-
190
- h4. Retrieving Multiple Objects in Batches
191
-
192
- We often need to iterate over a large set of records, as when we send a newsletter to a large set of users, or when we export data.
193
-
194
- This may appear straightforward:
195
-
196
- <ruby>
197
- # This is very inefficient when the users table has thousands of rows.
198
- User.all.each do |user|
199
- NewsLetter.weekly_deliver(user)
200
- end
201
- </ruby>
202
-
203
- But this approach becomes increasingly impractical as the table size increases, since +User.all.each+ instructs Active Record to fetch _the entire table_ in a single pass, build a model object per row, and then keep the entire array of model objects in memory. Indeed, if we have a large number of records, the entire collection may exceed the amount of memory available.
204
-
205
- Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing. The first method, +find_each+, retrieves a batch of records and then yields _each_ record to the block individually as a model. The second method, +find_in_batches+, retrieves a batch of records and then yields _the entire batch_ to the block as an array of models.
206
-
207
- TIP: The +find_each+ and +find_in_batches+ methods are intended for use in the batch processing of a large number of records that wouldn't fit in memory all at once. If you just need to loop over a thousand records the regular find methods are the preferred option.
208
-
209
- h5. +find_each+
210
-
211
- The +find_each+ method retrieves a batch of records and then yields _each_ record to the block individually as a model. In the following example, +find_each+ will retrieve 1000 records (the current default for both +find_each+ and +find_in_batches+) and then yield each record individually to the block as a model. This process is repeated until all of the records have been processed:
212
-
213
- <ruby>
214
- User.find_each do |user|
215
- NewsLetter.weekly_deliver(user)
216
- end
217
- </ruby>
218
-
219
- h6. Options for +find_each+
220
-
221
- The +find_each+ method accepts most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_each+.
222
-
223
- Two additional options, +:batch_size+ and +:start+, are available as well.
224
-
225
- *+:batch_size+*
226
-
227
- The +:batch_size+ option allows you to specify the number of records to be retrieved in each batch, before being passed individually to the block. For example, to retrieve records in batches of 5000:
228
-
229
- <ruby>
230
- User.find_each(:batch_size => 5000) do |user|
231
- NewsLetter.weekly_deliver(user)
232
- end
233
- </ruby>
234
-
235
- *+:start+*
236
-
237
- By default, records are fetched in ascending order of the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This would be useful, for example, if you wanted to resume an interrupted batch process, provided you saved the last processed ID as a checkpoint.
238
-
239
- For example, to send newsletters only to users with the primary key starting from 2000, and to retrieve them in batches of 5000:
240
-
241
- <ruby>
242
- User.find_each(:start => 2000, :batch_size => 5000) do |user|
243
- NewsLetter.weekly_deliver(user)
244
- end
245
- </ruby>
246
-
247
- Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate <tt>:start</tt> option on each worker.
248
-
249
- NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models.
250
-
251
- h5. +find_in_batches+
252
-
253
- The +find_in_batches+ method is similar to +find_each+, since both retrieve batches of records. The difference is that +find_in_batches+ yields _batches_ to the block as an array of models, instead of individually. The following example will yield to the supplied block an array of up to 1000 invoices at a time, with the final block containing any remaining invoices:
254
-
255
- <ruby>
256
- # Give add_invoices an array of 1000 invoices at a time
257
- Invoice.find_in_batches(:include => :invoice_lines) do |invoices|
258
- export.add_invoices(invoices)
259
- end
260
- </ruby>
261
-
262
- NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models.
263
-
264
- h6. Options for +find_in_batches+
265
-
266
- The +find_in_batches+ method accepts the same +:batch_size+ and +:start+ options as +find_each+, as well as most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_in_batches+.
267
-
268
- h3. Conditions
269
-
270
- The +where+ method allows you to specify conditions to limit the records returned, representing the +WHERE+-part of the SQL statement. Conditions can either be specified as a string, array, or hash.
271
-
272
- h4. Pure String Conditions
273
-
274
- If you'd like to add conditions to your find, you could just specify them in there, just like +Client.where("orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2.
275
-
276
- WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.where("first_name LIKE '%#{params[:first_name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array.
277
-
278
- h4. Array Conditions
279
-
280
- Now what if that number could vary, say as an argument from somewhere? The find would then take the form:
281
-
282
- <ruby>
283
- Client.where("orders_count = ?", params[:orders])
284
- </ruby>
285
-
286
- Active Record will go through the first element in the conditions value and any additional elements will replace the question marks +(?)+ in the first element.
287
-
288
- If you want to specify multiple conditions:
289
-
290
- <ruby>
291
- Client.where("orders_count = ? AND locked = ?", params[:orders], false)
292
- </ruby>
293
-
294
- In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with the SQL representation of +false+, which depends on the adapter.
295
-
296
- This code is highly preferable:
297
-
298
- <ruby>
299
- Client.where("orders_count = ?", params[:orders])
300
- </ruby>
301
-
302
- to this code:
303
-
304
- <ruby>
305
- Client.where("orders_count = #{params[:orders]}")
306
- </ruby>
307
-
308
- because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.
309
-
310
- TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection.
311
-
312
- h5. Placeholder Conditions
313
-
314
- Similar to the +(?)+ replacement style of params, you can also specify keys/values hash in your array conditions:
315
-
316
- <ruby>
317
- Client.where("created_at >= :start_date AND created_at <= :end_date",
318
- {:start_date => params[:start_date], :end_date => params[:end_date]})
319
- </ruby>
320
-
321
- This makes for clearer readability if you have a large number of variable conditions.
322
-
323
- h5(#array-range_conditions). Range Conditions
324
-
325
- If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the +IN+ SQL statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:
326
-
327
- <ruby>
328
- Client.where(:created_at => (params[:start_date].to_date)..(params[:end_date].to_date))
329
- </ruby>
330
-
331
- This query will generate something similar to the following SQL:
332
-
333
- <sql>
334
- SELECT "clients".* FROM "clients" WHERE ("clients"."created_at" BETWEEN '2010-09-29' AND '2010-11-30')
335
- </sql>
336
-
337
- h4. Hash Conditions
338
-
339
- Active Record also allows you to pass in hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them:
340
-
341
- NOTE: Only equality, range and subset checking are possible with Hash conditions.
342
-
343
- h5. Equality Conditions
344
-
345
- <ruby>
346
- Client.where(:locked => true)
347
- </ruby>
348
-
349
- The field name can also be a string:
350
-
351
- <ruby>
352
- Client.where('locked' => true)
353
- </ruby>
354
-
355
- h5(#hash-range_conditions). Range Conditions
356
-
357
- The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section.
358
-
359
- <ruby>
360
- Client.where(:created_at => (Time.now.midnight - 1.day)..Time.now.midnight)
361
- </ruby>
362
-
363
- This will find all clients created yesterday by using a +BETWEEN+ SQL statement:
364
-
365
- <sql>
366
- SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
367
- </sql>
368
-
369
- This demonstrates a shorter syntax for the examples in "Array Conditions":#array-conditions
370
-
371
- h5. Subset Conditions
372
-
373
- If you want to find records using the +IN+ expression you can pass an array to the conditions hash:
374
-
375
- <ruby>
376
- Client.where(:orders_count => [1,3,5])
377
- </ruby>
378
-
379
- This code will generate SQL like this:
380
-
381
- <sql>
382
- SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
383
- </sql>
384
-
385
- h3. Ordering
386
-
387
- To retrieve records from the database in a specific order, you can use the +order+ method.
388
-
389
- For example, if you're getting a set of records and want to order them in ascending order by the +created_at+ field in your table:
390
-
391
- <ruby>
392
- Client.order("created_at")
393
- </ruby>
394
-
395
- You could specify +ASC+ or +DESC+ as well:
396
-
397
- <ruby>
398
- Client.order("created_at DESC")
399
- # OR
400
- Client.order("created_at ASC")
401
- </ruby>
402
-
403
- Or ordering by multiple fields:
404
-
405
- <ruby>
406
- Client.order("orders_count ASC, created_at DESC")
407
- </ruby>
408
-
409
- h3. Selecting Specific Fields
410
-
411
- By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
412
-
413
- To select only a subset of fields from the result set, you can specify the subset via the +select+ method.
414
-
415
- NOTE: If the +select+ method is used, all the returning objects will be "read only":#readonly-objects.
416
-
417
- <br />
418
-
419
- For example, to select only +viewable_by+ and +locked+ columns:
420
-
421
- <ruby>
422
- Client.select("viewable_by, locked")
423
- </ruby>
424
-
425
- The SQL query used by this find call will be somewhat like:
426
-
427
- <sql>
428
- SELECT viewable_by, locked FROM clients
429
- </sql>
430
-
431
- Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive:
432
-
433
- <shell>
434
- ActiveModel::MissingAttributeError: missing attribute: <attribute>
435
- </shell>
436
-
437
- Where +&lt;attribute&gt;+ is the attribute you asked for. The +id+ method will not raise the +ActiveRecord::MissingAttributeError+, so just be careful when working with associations because they need the +id+ method to function properly.
438
-
439
- If you would like to only grab a single record per unique value in a certain field, you can use +uniq+:
440
-
441
- <ruby>
442
- Client.select(:name).uniq
443
- </ruby>
444
-
445
- This would generate SQL like:
446
-
447
- <sql>
448
- SELECT DISTINCT name FROM clients
449
- </sql>
450
-
451
- You can also remove the uniqueness constraint:
452
-
453
- <ruby>
454
- query = Client.select(:name).uniq
455
- # => Returns unique names
456
-
457
- query.uniq(false)
458
- # => Returns all names, even if there are duplicates
459
- </ruby>
460
-
461
- h3. Limit and Offset
462
-
463
- To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +limit+ and +offset+ methods on the relation.
464
-
465
- You can use +limit+ to specify the number of records to be retrieved, and use +offset+ to specify the number of records to skip before starting to return the records. For example
466
-
467
- <ruby>
468
- Client.limit(5)
469
- </ruby>
470
-
471
- will return a maximum of 5 clients and because it specifies no offset it will return the first 5 in the table. The SQL it executes looks like this:
472
-
473
- <sql>
474
- SELECT * FROM clients LIMIT 5
475
- </sql>
476
-
477
- Adding +offset+ to that
478
-
479
- <ruby>
480
- Client.limit(5).offset(30)
481
- </ruby>
482
-
483
- will return instead a maximum of 5 clients beginning with the 31st. The SQL looks like:
484
-
485
- <sql>
486
- SELECT * FROM clients LIMIT 5 OFFSET 30
487
- </sql>
488
-
489
- h3. Group
490
-
491
- To apply a +GROUP BY+ clause to the SQL fired by the finder, you can specify the +group+ method on the find.
492
-
493
- For example, if you want to find a collection of the dates orders were created on:
494
-
495
- <ruby>
496
- Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
497
- </ruby>
498
-
499
- And this will give you a single +Order+ object for each date where there are orders in the database.
500
-
501
- The SQL that would be executed would be something like this:
502
-
503
- <sql>
504
- SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at)
505
- </sql>
506
-
507
- h3. Having
508
-
509
- SQL uses the +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can add the +HAVING+ clause to the SQL fired by the +Model.find+ by adding the +:having+ option to the find.
510
-
511
- For example:
512
-
513
- <ruby>
514
- Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)").having("sum(price) > ?", 100)
515
- </ruby>
516
-
517
- The SQL that would be executed would be something like this:
518
-
519
- <sql>
520
- SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) HAVING sum(price) > 100
521
- </sql>
522
-
523
- This will return single order objects for each day, but only those that are ordered more than $100 in a day.
524
-
525
- h3. Overriding Conditions
526
-
527
- h4. +except+
528
-
529
- You can specify certain conditions to be excepted by using the +except+ method. For example:
530
-
531
- <ruby>
532
- Post.where('id > 10').limit(20).order('id asc').except(:order)
533
- </ruby>
534
-
535
- The SQL that would be executed:
536
-
537
- <sql>
538
- SELECT * FROM posts WHERE id > 10 LIMIT 20
539
- </sql>
540
-
541
- h4. +only+
542
-
543
- You can also override conditions using the +only+ method. For example:
544
-
545
- <ruby>
546
- Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
547
- </ruby>
548
-
549
- The SQL that would be executed:
550
-
551
- <sql>
552
- SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
553
- </sql>
554
-
555
- h4. +reorder+
556
-
557
- The +reorder+ method overrides the default scope order. For example:
558
-
559
- <ruby>
560
- class Post < ActiveRecord::Base
561
- ..
562
- ..
563
- has_many :comments, :order => 'posted_at DESC'
564
- end
565
-
566
- Post.find(10).comments.reorder('name')
567
- </ruby>
568
-
569
- The SQL that would be executed:
570
-
571
- <sql>
572
- SELECT * FROM posts WHERE id = 10 ORDER BY name
573
- </sql>
574
-
575
- In case the +reorder+ clause is not used, the SQL executed would be:
576
-
577
- <sql>
578
- SELECT * FROM posts WHERE id = 10 ORDER BY posted_at DESC
579
- </sql>
580
-
581
- h4. +reverse_order+
582
-
583
- The +reverse_order+ method reverses the ordering clause if specified.
584
-
585
- <ruby>
586
- Client.where("orders_count > 10").order(:name).reverse_order
587
- </ruby>
588
-
589
- The SQL that would be executed:
590
-
591
- <sql>
592
- SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC
593
- </sql>
594
-
595
- If no ordering clause is specified in the query, the +reverse_order+ orders by the primary key in reverse order.
596
-
597
- <ruby>
598
- Client.where("orders_count > 10").reverse_order
599
- </ruby>
600
-
601
- The SQL that would be executed:
602
-
603
- <sql>
604
- SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC
605
- </sql>
606
-
607
- This method accepts *no* arguments.
608
-
609
- h3. Readonly Objects
610
-
611
- Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception.
612
-
613
- <ruby>
614
- client = Client.readonly.first
615
- client.visits += 1
616
- client.save
617
- </ruby>
618
-
619
- As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visits_.
620
-
621
- h3. Locking Records for Update
622
-
623
- Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.
624
-
625
- Active Record provides two locking mechanisms:
626
-
627
- * Optimistic Locking
628
- * Pessimistic Locking
629
-
630
- h4. Optimistic Locking
631
-
632
- Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An +ActiveRecord::StaleObjectError+ exception is thrown if that has occurred and the update is ignored.
633
-
634
- <strong>Optimistic locking column</strong>
635
-
636
- In order to use optimistic locking, the table needs to have a column called +lock_version+. Each time the record is updated, Active Record increments the +lock_version+ column. If an update request is made with a lower value in the +lock_version+ field than is currently in the +lock_version+ column in the database, the update request will fail with an +ActiveRecord::StaleObjectError+. Example:
637
-
638
- <ruby>
639
- c1 = Client.find(1)
640
- c2 = Client.find(1)
641
-
642
- c1.first_name = "Michael"
643
- c1.save
644
-
645
- c2.name = "should fail"
646
- c2.save # Raises an ActiveRecord::StaleObjectError
647
- </ruby>
648
-
649
- You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict.
650
-
651
- NOTE: You must ensure that your database schema defaults the +lock_version+ column to +0+.
652
-
653
- This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
654
-
655
- To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class method called +set_locking_column+:
656
-
657
- <ruby>
658
- class Client < ActiveRecord::Base
659
- set_locking_column :lock_client_column
660
- end
661
- </ruby>
662
-
663
- h4. Pessimistic Locking
664
-
665
- Pessimistic locking uses a locking mechanism provided by the underlying database. Using +lock+ when building a relation obtains an exclusive lock on the selected rows. Relations using +lock+ are usually wrapped inside a transaction for preventing deadlock conditions.
666
-
667
- For example:
668
-
669
- <ruby>
670
- Item.transaction do
671
- i = Item.lock.first
672
- i.name = 'Jones'
673
- i.save
674
- end
675
- </ruby>
676
-
677
- The above session produces the following SQL for a MySQL backend:
678
-
679
- <sql>
680
- SQL (0.2ms) BEGIN
681
- Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
682
- Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
683
- SQL (0.8ms) COMMIT
684
- </sql>
685
-
686
- You can also pass raw SQL to the +lock+ method for allowing different types of locks. For example, MySQL has an expression called +LOCK IN SHARE MODE+ where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option:
687
-
688
- <ruby>
689
- Item.transaction do
690
- i = Item.lock("LOCK IN SHARE MODE").find(1)
691
- i.increment!(:views)
692
- end
693
- </ruby>
694
-
695
- If you already have an instance of your model, you can start a transaction and acquire the lock in one go using the following code:
696
-
697
- <ruby>
698
- item = Item.first
699
- item.with_lock do
700
- # This block is called within a transaction,
701
- # item is already locked.
702
- item.increment!(:views)
703
- end
704
- </ruby>
705
-
706
- h3. Joining Tables
707
-
708
- Active Record provides a finder method called +joins+ for specifying +JOIN+ clauses on the resulting SQL. There are multiple ways to use the +joins+ method.
709
-
710
- h4. Using a String SQL Fragment
711
-
712
- You can just supply the raw SQL specifying the +JOIN+ clause to +joins+:
713
-
714
- <ruby>
715
- Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
716
- </ruby>
717
-
718
- This will result in the following SQL:
719
-
720
- <sql>
721
- SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
722
- </sql>
723
-
724
- h4. Using Array/Hash of Named Associations
725
-
726
- WARNING: This method only works with +INNER JOIN+.
727
-
728
- Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying +JOIN+ clause for those associations when using the +joins+ method.
729
-
730
- For example, consider the following +Category+, +Post+, +Comments+ and +Guest+ models:
731
-
732
- <ruby>
733
- class Category < ActiveRecord::Base
734
- has_many :posts
735
- end
736
-
737
- class Post < ActiveRecord::Base
738
- belongs_to :category
739
- has_many :comments
740
- has_many :tags
741
- end
742
-
743
- class Comment < ActiveRecord::Base
744
- belongs_to :post
745
- has_one :guest
746
- end
747
-
748
- class Guest < ActiveRecord::Base
749
- belongs_to :comment
750
- end
751
-
752
- class Tag < ActiveRecord::Base
753
- belongs_to :post
754
- end
755
- </ruby>
756
-
757
- Now all of the following will produce the expected join queries using +INNER JOIN+:
758
-
759
- h5. Joining a Single Association
760
-
761
- <ruby>
762
- Category.joins(:posts)
763
- </ruby>
764
-
765
- This produces:
766
-
767
- <sql>
768
- SELECT categories.* FROM categories
769
- INNER JOIN posts ON posts.category_id = categories.id
770
- </sql>
771
-
772
- Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:post).select("distinct(categories.id)").
773
-
774
- h5. Joining Multiple Associations
775
-
776
- <ruby>
777
- Post.joins(:category, :comments)
778
- </ruby>
779
-
780
- This produces:
781
-
782
- <sql>
783
- SELECT posts.* FROM posts
784
- INNER JOIN categories ON posts.category_id = categories.id
785
- INNER JOIN comments ON comments.post_id = posts.id
786
- </sql>
787
-
788
- Or, in English: "return all posts that have a category and at least one comment". Note again that posts with multiple comments will show up multiple times.
789
-
790
- h5. Joining Nested Associations (Single Level)
791
-
792
- <ruby>
793
- Post.joins(:comments => :guest)
794
- </ruby>
795
-
796
- This produces:
797
-
798
- <sql>
799
- SELECT posts.* FROM posts
800
- INNER JOIN comments ON comments.post_id = posts.id
801
- INNER JOIN guests ON guests.comment_id = comments.id
802
- </sql>
803
-
804
- Or, in English: "return all posts that have a comment made by a guest."
805
-
806
- h5. Joining Nested Associations (Multiple Level)
807
-
808
- <ruby>
809
- Category.joins(:posts => [{:comments => :guest}, :tags])
810
- </ruby>
811
-
812
- This produces:
813
-
814
- <sql>
815
- SELECT categories.* FROM categories
816
- INNER JOIN posts ON posts.category_id = categories.id
817
- INNER JOIN comments ON comments.post_id = posts.id
818
- INNER JOIN guests ON guests.comment_id = comments.id
819
- INNER JOIN tags ON tags.post_id = posts.id
820
- </sql>
821
-
822
- h4. Specifying Conditions on the Joined Tables
823
-
824
- You can specify conditions on the joined tables using the regular "Array":#array-conditions and "String":#pure-string-conditions conditions. "Hash conditions":#hash-conditions provides a special syntax for specifying conditions for the joined tables:
825
-
826
- <ruby>
827
- time_range = (Time.now.midnight - 1.day)..Time.now.midnight
828
- Client.joins(:orders).where('orders.created_at' => time_range)
829
- </ruby>
830
-
831
- An alternative and cleaner syntax is to nest the hash conditions:
832
-
833
- <ruby>
834
- time_range = (Time.now.midnight - 1.day)..Time.now.midnight
835
- Client.joins(:orders).where(:orders => {:created_at => time_range})
836
- </ruby>
837
-
838
- This will find all clients who have orders that were created yesterday, again using a +BETWEEN+ SQL expression.
839
-
840
- h3. Eager Loading Associations
841
-
842
- Eager loading is the mechanism for loading the associated records of the objects returned by +Model.find+ using as few queries as possible.
843
-
844
- <strong>N <plus> 1 queries problem</strong>
845
-
846
- Consider the following code, which finds 10 clients and prints their postcodes:
847
-
848
- <ruby>
849
- clients = Client.limit(10)
850
-
851
- clients.each do |client|
852
- puts client.address.postcode
853
- end
854
- </ruby>
855
-
856
- This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 ( to find 10 clients ) <plus> 10 ( one per each client to load the address ) = <strong>11</strong> queries in total.
857
-
858
- <strong>Solution to N <plus> 1 queries problem</strong>
859
-
860
- Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the +includes+ method of the +Model.find+ call. With +includes+, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.
861
-
862
- Revisiting the above case, we could rewrite +Client.all+ to use eager load addresses:
863
-
864
- <ruby>
865
- clients = Client.includes(:address).limit(10)
866
-
867
- clients.each do |client|
868
- puts client.address.postcode
869
- end
870
- </ruby>
871
-
872
- The above code will execute just <strong>2</strong> queries, as opposed to <strong>11</strong> queries in the previous case:
873
-
874
- <sql>
875
- SELECT * FROM clients LIMIT 10
876
- SELECT addresses.* FROM addresses
877
- WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
878
- </sql>
879
-
880
- h4. Eager Loading Multiple Associations
881
-
882
- Active Record lets you eager load any number of associations with a single +Model.find+ call by using an array, hash, or a nested hash of array/hash with the +includes+ method.
883
-
884
- h5. Array of Multiple Associations
885
-
886
- <ruby>
887
- Post.includes(:category, :comments)
888
- </ruby>
889
-
890
- This loads all the posts and the associated category and comments for each post.
891
-
892
- h5. Nested Associations Hash
893
-
894
- <ruby>
895
- Category.includes(:posts => [{:comments => :guest}, :tags]).find(1)
896
- </ruby>
897
-
898
- This will find the category with id 1 and eager load all of the associated posts, the associated posts' tags and comments, and every comment's guest association.
899
-
900
- h4. Specifying Conditions on Eager Loaded Associations
901
-
902
- Even though Active Record lets you specify conditions on the eager loaded associations just like +joins+, the recommended way is to use "joins":#joining-tables instead.
903
-
904
- However if you must do this, you may use +where+ as you would normally.
905
-
906
- <ruby>
907
- Post.includes(:comments).where("comments.visible", true)
908
- </ruby>
909
-
910
- This would generate a query which contains a +LEFT OUTER JOIN+ whereas the +joins+ method would generate one using the +INNER JOIN+ function instead.
911
-
912
- <ruby>
913
- SELECT "posts"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5 FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE (comments.visible = 1)
914
- </ruby>
915
-
916
- If there was no +where+ condition, this would generate the normal set of two queries.
917
-
918
- If, in the case of this +includes+ query, there were no comments for any posts, all the posts would still be loaded. By using +joins+ (an INNER JOIN), the join conditions *must* match, otherwise no records will be returned.
919
-
920
- h3. Scopes
921
-
922
- Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it.
923
-
924
- To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called:
925
-
926
- <ruby>
927
- class Post < ActiveRecord::Base
928
- scope :published, where(:published => true)
929
- end
930
- </ruby>
931
-
932
- Just like before, these methods are also chainable:
933
-
934
- <ruby>
935
- class Post < ActiveRecord::Base
936
- scope :published, where(:published => true).joins(:category)
937
- end
938
- </ruby>
939
-
940
- Scopes are also chainable within scopes:
941
-
942
- <ruby>
943
- class Post < ActiveRecord::Base
944
- scope :published, where(:published => true)
945
- scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
946
- end
947
- </ruby>
948
-
949
- To call this +published+ scope we can call it on either the class:
950
-
951
- <ruby>
952
- Post.published # => [published posts]
953
- </ruby>
954
-
955
- Or on an association consisting of +Post+ objects:
956
-
957
- <ruby>
958
- category = Category.first
959
- category.posts.published # => [published posts belonging to this category]
960
- </ruby>
961
-
962
- h4. Working with times
963
-
964
- If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time.
965
-
966
- <ruby>
967
- class Post < ActiveRecord::Base
968
- scope :last_week, lambda { where("created_at < ?", Time.zone.now ) }
969
- end
970
- </ruby>
971
-
972
- Without the +lambda+, this +Time.zone.now+ will only be called once.
973
-
974
- h4. Passing in arguments
975
-
976
- When a +lambda+ is used for a +scope+, it can take arguments:
977
-
978
- <ruby>
979
- class Post < ActiveRecord::Base
980
- scope :1_week_before, lambda { |time| where("created_at < ?", time) }
981
- end
982
- </ruby>
983
-
984
- This may then be called using this:
985
-
986
- <ruby>
987
- Post.1_week_before(Time.zone.now)
988
- </ruby>
989
-
990
- However, this is just duplicating the functionality that would be provided to you by a class method.
991
-
992
- <ruby>
993
- class Post < ActiveRecord::Base
994
- def self.1_week_before(time)
995
- where("created_at < ?", time)
996
- end
997
- end
998
- </ruby>
999
-
1000
- Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:
1001
-
1002
- <ruby>
1003
- category.posts.1_week_before(time)
1004
- </ruby>
1005
-
1006
- h4. Working with scopes
1007
-
1008
- Where a relational object is required, the +scoped+ method may come in handy. This will return an +ActiveRecord::Relation+ object which can have further scoping applied to it afterwards. A place where this may come in handy is on associations
1009
-
1010
- <ruby>
1011
- client = Client.find_by_first_name("Ryan")
1012
- orders = client.orders.scoped
1013
- </ruby>
1014
-
1015
- With this new +orders+ object, we are able to ascertain that this object can have more scopes applied to it. For instance, if we wanted to return orders only in the last 30 days at a later point.
1016
-
1017
- <ruby>
1018
- orders.where("created_at > ?", 30.days.ago)
1019
- </ruby>
1020
-
1021
- h4. Applying a default scope
1022
-
1023
- If we wish for a scope to be applied across all queries to the model we can use the +default_scope+ method within the model itself.
1024
-
1025
- <ruby>
1026
- class Client < ActiveRecord::Base
1027
- default_scope where("removed_at IS NULL")
1028
- end
1029
- </ruby>
1030
-
1031
- When queries are executed on this model, the SQL query will now look something like this:
1032
-
1033
- <sql>
1034
- SELECT * FROM clients WHERE removed_at IS NULL
1035
- </sql>
1036
-
1037
- h4. Removing all scoping
1038
-
1039
- If we wish to remove scoping for any reason we can use the +unscoped+ method. This is especially useful if a +default_scope+ is specified in the model and should not be applied for this particular query.
1040
-
1041
- <ruby>
1042
- Client.unscoped.all
1043
- </ruby>
1044
-
1045
- This method removes all scoping and will do a normal query on the table.
1046
-
1047
- h3. Dynamic Finders
1048
-
1049
- For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods.
1050
-
1051
- You can also use +find_last_by_*+ methods which will find the last record matching your argument.
1052
-
1053
- You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+
1054
-
1055
- If you want to find both by name and locked, you can chain these finders together by simply typing "+and+" between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+.
1056
-
1057
- WARNING: Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say <tt>Client.find_by_name_and_locked("Ryan")</tt>, the behavior is to pass +nil+ as the missing argument. This is *unintentional* and this behavior will be changed in Rails 3.2 to throw an +ArgumentError+.
1058
-
1059
- h3. Find or build a new object
1060
-
1061
- It's common that you need to find a record or create it if it doesn't exist. You can do that with the +first_or_create+ and +first_or_create!+ methods.
1062
-
1063
- h4. +first_or_create+
1064
-
1065
- The +first_or_create+ method checks whether +first+ returns +nil+ or not. If it does return +nil+, then +create+ is called. This is very powerful when coupled with the +where+ method. Let's see an example.
1066
-
1067
- Suppose you want to find a client named 'Andy', and if there's none, create one and additionally set his +locked+ attribute to false. You can do so by running:
1068
-
1069
- <ruby>
1070
- Client.where(:first_name => 'Andy').first_or_create(:locked => false)
1071
- # => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
1072
- </ruby>
1073
-
1074
- The SQL generated by this method looks like this:
1075
-
1076
- <sql>
1077
- SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
1078
- BEGIN
1079
- INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 0, NULL, '2011-08-30 05:22:57')
1080
- COMMIT
1081
- </sql>
1082
-
1083
- +first_or_create+ returns either the record that already exists or the new record. In our case, we didn't already have a client named Andy so the record is created and returned.
1084
-
1085
- The new record might not be saved to the database; that depends on whether validations passed or not (just like +create+).
1086
-
1087
- It's also worth noting that +first_or_create+ takes into account the arguments of the +where+ method. In the example above we didn't explicitly pass a +:first_name => 'Andy'+ argument to +first_or_create+. However, that was used when creating the new record because it was already passed before to the +where+ method.
1088
-
1089
- You can do the same with the +find_or_create_by+ method:
1090
-
1091
- <ruby>
1092
- Client.find_or_create_by_first_name(:first_name => "Andy", :locked => false)
1093
- </ruby>
1094
-
1095
- This method still works, but it's encouraged to use +first_or_create+ because it's more explicit on which arguments are used to _find_ the record and which are used to _create_, resulting in less confusion overall.
1096
-
1097
- h4. +first_or_create!+
1098
-
1099
- You can also use +first_or_create!+ to raise an exception if the new record is invalid. Validations are not covered on this guide, but let's assume for a moment that you temporarily add
1100
-
1101
- <ruby>
1102
- validates :orders_count, :presence => true
1103
- </ruby>
1104
-
1105
- to your +Client+ model. If you try to create a new +Client+ without passing an +orders_count+, the record will be invalid and an exception will be raised:
1106
-
1107
- <ruby>
1108
- Client.where(:first_name => 'Andy').first_or_create!(:locked => false)
1109
- # => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
1110
- </ruby>
1111
-
1112
- As with +first_or_create+ there is a +find_or_create_by!+ method but the +first_or_create!+ method is preferred for clarity.
1113
-
1114
- h4. +first_or_initialize+
1115
-
1116
- The +first_or_initialize+ method will work just like +first_or_create+ but it will not call +create+ but +new+. This means that a new model instance will be created in memory but won't be saved to the database. Continuing with the +first_or_create+ example, we now want the client named 'Nick':
1117
-
1118
- <ruby>
1119
- nick = Client.where(:first_name => 'Nick').first_or_initialize(:locked => false)
1120
- # => <Client id: nil, first_name: "Nick", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
1121
-
1122
- nick.persisted?
1123
- # => false
1124
-
1125
- nick.new_record?
1126
- # => true
1127
- </ruby>
1128
-
1129
- Because the object is not yet stored in the database, the SQL generated looks like this:
1130
-
1131
- <sql>
1132
- SELECT * FROM clients WHERE (clients.first_name = 'Nick') LIMIT 1
1133
- </sql>
1134
-
1135
- When you want to save it to the database, just call +save+:
1136
-
1137
- <ruby>
1138
- nick.save
1139
- # => true
1140
- </ruby>
1141
-
1142
- h3. Finding by SQL
1143
-
1144
- If you'd like to use your own SQL to find records in a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if the underlying query returns just a single record. For example you could run this query:
1145
-
1146
- <ruby>
1147
- Client.find_by_sql("SELECT * FROM clients
1148
- INNER JOIN orders ON clients.id = orders.client_id
1149
- ORDER clients.created_at desc")
1150
- </ruby>
1151
-
1152
- +find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
1153
-
1154
- h3. +select_all+
1155
-
1156
- <tt>find_by_sql</tt> has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
1157
-
1158
- <ruby>
1159
- Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
1160
- </ruby>
1161
-
1162
- h3. +pluck+
1163
-
1164
- <tt>pluck</tt> can be used to query a single column from the underlying table of a model. It accepts a column name as argument and returns an array of values of the specified column with the corresponding data type.
1165
-
1166
- <ruby>
1167
- Client.where(:active => true).pluck(:id)
1168
- # SELECT id FROM clients WHERE active = 1
1169
-
1170
- Client.uniq.pluck(:role)
1171
- # SELECT DISTINCT role FROM clients
1172
- </ruby>
1173
-
1174
- +pluck+ makes it possible to replace code like
1175
-
1176
- <ruby>
1177
- Client.select(:id).map { |c| c.id }
1178
- </ruby>
1179
-
1180
- with
1181
-
1182
- <ruby>
1183
- Client.pluck(:id)
1184
- </ruby>
1185
-
1186
- h3. Existence of Objects
1187
-
1188
- If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as +find+, but instead of returning an object or collection of objects it will return either +true+ or +false+.
1189
-
1190
- <ruby>
1191
- Client.exists?(1)
1192
- </ruby>
1193
-
1194
- The +exists?+ method also takes multiple ids, but the catch is that it will return true if any one of those records exists.
1195
-
1196
- <ruby>
1197
- Client.exists?(1,2,3)
1198
- # or
1199
- Client.exists?([1,2,3])
1200
- </ruby>
1201
-
1202
- It's even possible to use +exists?+ without any arguments on a model or a relation.
1203
-
1204
- <ruby>
1205
- Client.where(:first_name => 'Ryan').exists?
1206
- </ruby>
1207
-
1208
- The above returns +true+ if there is at least one client with the +first_name+ 'Ryan' and +false+ otherwise.
1209
-
1210
- <ruby>
1211
- Client.exists?
1212
- </ruby>
1213
-
1214
- The above returns +false+ if the +clients+ table is empty and +true+ otherwise.
1215
-
1216
- You can also use +any?+ and +many?+ to check for existence on a model or relation.
1217
-
1218
- <ruby>
1219
- # via a model
1220
- Post.any?
1221
- Post.many?
1222
-
1223
- # via a named scope
1224
- Post.recent.any?
1225
- Post.recent.many?
1226
-
1227
- # via a relation
1228
- Post.where(:published => true).any?
1229
- Post.where(:published => true).many?
1230
-
1231
- # via an association
1232
- Post.first.categories.any?
1233
- Post.first.categories.many?
1234
- </ruby>
1235
-
1236
- h3. Calculations
1237
-
1238
- This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
1239
-
1240
- All calculation methods work directly on a model:
1241
-
1242
- <ruby>
1243
- Client.count
1244
- # SELECT count(*) AS count_all FROM clients
1245
- </ruby>
1246
-
1247
- Or on a relation:
1248
-
1249
- <ruby>
1250
- Client.where(:first_name => 'Ryan').count
1251
- # SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
1252
- </ruby>
1253
-
1254
- You can also use various finder methods on a relation for performing complex calculations:
1255
-
1256
- <ruby>
1257
- Client.includes("orders").where(:first_name => 'Ryan', :orders => {:status => 'received'}).count
1258
- </ruby>
1259
-
1260
- Which will execute:
1261
-
1262
- <sql>
1263
- SELECT count(DISTINCT clients.id) AS count_all FROM clients
1264
- LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
1265
- (clients.first_name = 'Ryan' AND orders.status = 'received')
1266
- </sql>
1267
-
1268
- h4. Count
1269
-
1270
- If you want to see how many records are in your model's table you could call +Client.count+ and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use +Client.count(:age)+.
1271
-
1272
- For options, please see the parent section, "Calculations":#calculations.
1273
-
1274
- h4. Average
1275
-
1276
- If you want to see the average of a certain number in one of your tables you can call the +average+ method on the class that relates to the table. This method call will look something like this:
1277
-
1278
- <ruby>
1279
- Client.average("orders_count")
1280
- </ruby>
1281
-
1282
- This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
1283
-
1284
- For options, please see the parent section, "Calculations":#calculations.
1285
-
1286
- h4. Minimum
1287
-
1288
- If you want to find the minimum value of a field in your table you can call the +minimum+ method on the class that relates to the table. This method call will look something like this:
1289
-
1290
- <ruby>
1291
- Client.minimum("age")
1292
- </ruby>
1293
-
1294
- For options, please see the parent section, "Calculations":#calculations.
1295
-
1296
- h4. Maximum
1297
-
1298
- If you want to find the maximum value of a field in your table you can call the +maximum+ method on the class that relates to the table. This method call will look something like this:
1299
-
1300
- <ruby>
1301
- Client.maximum("age")
1302
- </ruby>
1303
-
1304
- For options, please see the parent section, "Calculations":#calculations.
1305
-
1306
- h4. Sum
1307
-
1308
- If you want to find the sum of a field for all records in your table you can call the +sum+ method on the class that relates to the table. This method call will look something like this:
1309
-
1310
- <ruby>
1311
- Client.sum("orders_count")
1312
- </ruby>
1313
-
1314
- For options, please see the parent section, "Calculations":#calculations.
1315
-
1316
- h3. Running EXPLAIN
1317
-
1318
- You can run EXPLAIN on the queries triggered by relations. For example,
1319
-
1320
- <ruby>
1321
- User.where(:id => 1).joins(:posts).explain
1322
- </ruby>
1323
-
1324
- may yield
1325
-
1326
- <plain>
1327
- EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `posts` ON `posts`.`user_id` = `users`.`id` WHERE `users`.`id` = 1
1328
- <plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------------<plus>
1329
- | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
1330
- <plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------------<plus>
1331
- | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
1332
- | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
1333
- <plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------------<plus>
1334
- 2 rows in set (0.00 sec)
1335
- </plain>
1336
-
1337
- under MySQL.
1338
-
1339
- Active Record performs a pretty printing that emulates the one of the database
1340
- shells. So, the same query running with the PostgreSQL adapter would yield instead
1341
-
1342
- <plain>
1343
- EXPLAIN for: SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" WHERE "users"."id" = 1
1344
- QUERY PLAN
1345
- ------------------------------------------------------------------------------
1346
- Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
1347
- Join Filter: (posts.user_id = users.id)
1348
- -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
1349
- Index Cond: (id = 1)
1350
- -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4)
1351
- Filter: (posts.user_id = 1)
1352
- (6 rows)
1353
- </plain>
1354
-
1355
- Eager loading may trigger more than one query under the hood, and some queries
1356
- may need the results of previous ones. Because of that, +explain+ actually
1357
- executes the query, and then asks for the query plans. For example,
1358
-
1359
- <ruby>
1360
- User.where(:id => 1).includes(:posts).explain
1361
- </ruby>
1362
-
1363
- yields
1364
-
1365
- <plain>
1366
- EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
1367
- <plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------<plus>
1368
- | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
1369
- <plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------<plus>
1370
- | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
1371
- <plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------<plus>
1372
- 1 row in set (0.00 sec)
1373
-
1374
- EXPLAIN for: SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1)
1375
- <plus>----<plus>-------------<plus>-------<plus>------<plus>---------------<plus>------<plus>---------<plus>------<plus>------<plus>-------------<plus>
1376
- | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
1377
- <plus>----<plus>-------------<plus>-------<plus>------<plus>---------------<plus>------<plus>---------<plus>------<plus>------<plus>-------------<plus>
1378
- | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
1379
- <plus>----<plus>-------------<plus>-------<plus>------<plus>---------------<plus>------<plus>---------<plus>------<plus>------<plus>-------------<plus>
1380
- 1 row in set (0.00 sec)
1381
- </plain>
1382
-
1383
- under MySQL.
1384
-
1385
- h4. Automatic EXPLAIN
1386
-
1387
- Active Record is able to run EXPLAIN automatically on slow queries and log its
1388
- output. This feature is controlled by the configuration parameter
1389
-
1390
- <ruby>
1391
- config.active_record.auto_explain_threshold_in_seconds
1392
- </ruby>
1393
-
1394
- If set to a number, any query exceeding those many seconds will have its EXPLAIN
1395
- automatically triggered and logged. In the case of relations, the threshold is
1396
- compared to the total time needed to fetch records. So, a relation is seen as a
1397
- unit of work, no matter whether the implementation of eager loading involves
1398
- several queries under the hood.
1399
-
1400
- A threshold of +nil+ disables automatic EXPLAINs.
1401
-
1402
- The default threshold in development mode is 0.5 seconds, and +nil+ in test and
1403
- production modes.
1404
-
1405
- INFO. Automatic EXPLAIN gets disabled if Active Record has no logger, regardless
1406
- of the value of the threshold.
1407
-
1408
- h5. Disabling Automatic EXPLAIN
1409
-
1410
- Automatic EXPLAIN can be selectively silenced with +ActiveRecord::Base.silence_auto_explain+:
1411
-
1412
- <ruby>
1413
- ActiveRecord::Base.silence_auto_explain do
1414
- # no automatic EXPLAIN is triggered here
1415
- end
1416
- </ruby>
1417
-
1418
- That may be useful for queries you know are slow but fine, like a heavyweight
1419
- report of an admin interface.
1420
-
1421
- As its name suggests, +silence_auto_explain+ only silences automatic EXPLAINs.
1422
- Explicit calls to +ActiveRecord::Relation#explain+ run.
1423
-
1424
- h4. Interpreting EXPLAIN
1425
-
1426
- Interpretation of the output of EXPLAIN is beyond the scope of this guide. The
1427
- following pointers may be helpful:
1428
-
1429
- * SQLite3: "EXPLAIN QUERY PLAN":http://www.sqlite.org/eqp.html
1430
-
1431
- * MySQL: "EXPLAIN Output Format":http://dev.mysql.com/doc/refman/5.6/en/explain-output.html
1432
-
1433
- * PostgreSQL: "Using EXPLAIN":http://www.postgresql.org/docs/current/static/using-explain.html