openskies 0.0.5.2 → 0.0.6.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (491) hide show
  1. data/CHANGELOG.md +0 -87
  2. data/bin/openskies +31 -5
  3. metadata +4 -593
  4. data/guides/assets/images/belongs_to.png +0 -0
  5. data/guides/assets/images/book_icon.gif +0 -0
  6. data/guides/assets/images/bullet.gif +0 -0
  7. data/guides/assets/images/challenge.png +0 -0
  8. data/guides/assets/images/chapters_icon.gif +0 -0
  9. data/guides/assets/images/check_bullet.gif +0 -0
  10. data/guides/assets/images/credits_pic_blank.gif +0 -0
  11. data/guides/assets/images/csrf.png +0 -0
  12. data/guides/assets/images/customized_error_messages.png +0 -0
  13. data/guides/assets/images/edge_badge.png +0 -0
  14. data/guides/assets/images/error_messages.png +0 -0
  15. data/guides/assets/images/feature_tile.gif +0 -0
  16. data/guides/assets/images/footer_tile.gif +0 -0
  17. data/guides/assets/images/fxn.png +0 -0
  18. data/guides/assets/images/grey_bullet.gif +0 -0
  19. data/guides/assets/images/habtm.png +0 -0
  20. data/guides/assets/images/has_many.png +0 -0
  21. data/guides/assets/images/has_many_through.png +0 -0
  22. data/guides/assets/images/has_one.png +0 -0
  23. data/guides/assets/images/has_one_through.png +0 -0
  24. data/guides/assets/images/header_backdrop.png +0 -0
  25. data/guides/assets/images/header_tile.gif +0 -0
  26. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  27. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  28. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  29. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  30. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  31. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  32. data/guides/assets/images/icons/README +0 -5
  33. data/guides/assets/images/icons/callouts/1.png +0 -0
  34. data/guides/assets/images/icons/callouts/10.png +0 -0
  35. data/guides/assets/images/icons/callouts/11.png +0 -0
  36. data/guides/assets/images/icons/callouts/12.png +0 -0
  37. data/guides/assets/images/icons/callouts/13.png +0 -0
  38. data/guides/assets/images/icons/callouts/14.png +0 -0
  39. data/guides/assets/images/icons/callouts/15.png +0 -0
  40. data/guides/assets/images/icons/callouts/2.png +0 -0
  41. data/guides/assets/images/icons/callouts/3.png +0 -0
  42. data/guides/assets/images/icons/callouts/4.png +0 -0
  43. data/guides/assets/images/icons/callouts/5.png +0 -0
  44. data/guides/assets/images/icons/callouts/6.png +0 -0
  45. data/guides/assets/images/icons/callouts/7.png +0 -0
  46. data/guides/assets/images/icons/callouts/8.png +0 -0
  47. data/guides/assets/images/icons/callouts/9.png +0 -0
  48. data/guides/assets/images/icons/caution.png +0 -0
  49. data/guides/assets/images/icons/example.png +0 -0
  50. data/guides/assets/images/icons/home.png +0 -0
  51. data/guides/assets/images/icons/important.png +0 -0
  52. data/guides/assets/images/icons/next.png +0 -0
  53. data/guides/assets/images/icons/note.png +0 -0
  54. data/guides/assets/images/icons/prev.png +0 -0
  55. data/guides/assets/images/icons/tip.png +0 -0
  56. data/guides/assets/images/icons/up.png +0 -0
  57. data/guides/assets/images/icons/warning.png +0 -0
  58. data/guides/assets/images/jaimeiniesta.jpg +0 -0
  59. data/guides/assets/images/nav_arrow.gif +0 -0
  60. data/guides/assets/images/polymorphic.png +0 -0
  61. data/guides/assets/images/posts_index.png +0 -0
  62. data/guides/assets/images/radar.png +0 -0
  63. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  64. data/guides/assets/images/rails_guides_logo.gif +0 -0
  65. data/guides/assets/images/rails_logo_remix.gif +0 -0
  66. data/guides/assets/images/rails_welcome.png +0 -0
  67. data/guides/assets/images/session_fixation.png +0 -0
  68. data/guides/assets/images/tab_grey.gif +0 -0
  69. data/guides/assets/images/tab_info.gif +0 -0
  70. data/guides/assets/images/tab_note.gif +0 -0
  71. data/guides/assets/images/tab_red.gif +0 -0
  72. data/guides/assets/images/tab_yellow.gif +0 -0
  73. data/guides/assets/images/tab_yellow.png +0 -0
  74. data/guides/assets/images/validation_error_messages.png +0 -0
  75. data/guides/assets/images/vijaydev.jpg +0 -0
  76. data/guides/assets/javascripts/guides.js +0 -7
  77. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  78. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  79. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  80. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  81. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  82. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  83. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  84. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  85. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  86. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  87. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  88. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  89. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  90. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  91. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  102. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  103. data/guides/assets/stylesheets/fixes.css +0 -16
  104. data/guides/assets/stylesheets/kindle.css +0 -11
  105. data/guides/assets/stylesheets/main.css +0 -453
  106. data/guides/assets/stylesheets/print.css +0 -52
  107. data/guides/assets/stylesheets/reset.css +0 -43
  108. data/guides/assets/stylesheets/style.css +0 -13
  109. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  110. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  111. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  112. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  113. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  114. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  115. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  116. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  117. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  118. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  119. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  120. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  121. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  122. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  123. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  124. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  125. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  126. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  127. data/guides/code/getting_started/Gemfile +0 -38
  128. data/guides/code/getting_started/README.rdoc +0 -261
  129. data/guides/code/getting_started/Rakefile +0 -7
  130. data/guides/code/getting_started/app/assets/images/rails.png +0 -0
  131. data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
  132. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
  133. data/guides/code/getting_started/app/assets/javascripts/home.js.coffee +0 -3
  134. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
  135. data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
  136. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
  137. data/guides/code/getting_started/app/assets/stylesheets/home.css.scss +0 -3
  138. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
  139. data/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss +0 -56
  140. data/guides/code/getting_started/app/controllers/application_controller.rb +0 -3
  141. data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -16
  142. data/guides/code/getting_started/app/controllers/home_controller.rb +0 -5
  143. data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -84
  144. data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
  145. data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
  146. data/guides/code/getting_started/app/helpers/home_helper.rb +0 -2
  147. data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -5
  148. data/guides/code/getting_started/app/models/comment.rb +0 -3
  149. data/guides/code/getting_started/app/models/post.rb +0 -11
  150. data/guides/code/getting_started/app/models/tag.rb +0 -3
  151. data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
  152. data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
  153. data/guides/code/getting_started/app/views/home/index.html.erb +0 -2
  154. data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
  155. data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -32
  156. data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -6
  157. data/guides/code/getting_started/app/views/posts/index.html.erb +0 -27
  158. data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
  159. data/guides/code/getting_started/app/views/posts/show.html.erb +0 -31
  160. data/guides/code/getting_started/app/views/tags/_form.html.erb +0 -12
  161. data/guides/code/getting_started/config/application.rb +0 -59
  162. data/guides/code/getting_started/config/boot.rb +0 -6
  163. data/guides/code/getting_started/config/database.yml +0 -25
  164. data/guides/code/getting_started/config/environment.rb +0 -5
  165. data/guides/code/getting_started/config/environments/development.rb +0 -37
  166. data/guides/code/getting_started/config/environments/production.rb +0 -67
  167. data/guides/code/getting_started/config/environments/test.rb +0 -37
  168. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  169. data/guides/code/getting_started/config/initializers/inflections.rb +0 -15
  170. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  171. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -7
  172. data/guides/code/getting_started/config/initializers/session_store.rb +0 -8
  173. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  174. data/guides/code/getting_started/config/locales/en.yml +0 -5
  175. data/guides/code/getting_started/config/routes.rb +0 -64
  176. data/guides/code/getting_started/config.ru +0 -4
  177. data/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb +0 -11
  178. data/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb +0 -12
  179. data/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb +0 -11
  180. data/guides/code/getting_started/db/schema.rb +0 -43
  181. data/guides/code/getting_started/db/seeds.rb +0 -7
  182. data/guides/code/getting_started/doc/README_FOR_APP +0 -2
  183. data/guides/code/getting_started/public/404.html +0 -26
  184. data/guides/code/getting_started/public/422.html +0 -26
  185. data/guides/code/getting_started/public/500.html +0 -25
  186. data/guides/code/getting_started/public/favicon.ico +0 -0
  187. data/guides/code/getting_started/public/robots.txt +0 -5
  188. data/guides/code/getting_started/script/rails +0 -6
  189. data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
  190. data/guides/code/getting_started/test/fixtures/posts.yml +0 -11
  191. data/guides/code/getting_started/test/fixtures/tags.yml +0 -9
  192. data/guides/code/getting_started/test/functional/comments_controller_test.rb +0 -7
  193. data/guides/code/getting_started/test/functional/home_controller_test.rb +0 -9
  194. data/guides/code/getting_started/test/functional/posts_controller_test.rb +0 -49
  195. data/guides/code/getting_started/test/performance/browsing_test.rb +0 -12
  196. data/guides/code/getting_started/test/test_helper.rb +0 -13
  197. data/guides/code/getting_started/test/unit/comment_test.rb +0 -7
  198. data/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb +0 -4
  199. data/guides/code/getting_started/test/unit/helpers/home_helper_test.rb +0 -4
  200. data/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb +0 -4
  201. data/guides/code/getting_started/test/unit/post_test.rb +0 -7
  202. data/guides/code/getting_started/test/unit/tag_test.rb +0 -7
  203. data/guides/rails_guides/generator.rb +0 -310
  204. data/guides/rails_guides/helpers.rb +0 -45
  205. data/guides/rails_guides/indexer.rb +0 -69
  206. data/guides/rails_guides/levenshtein.rb +0 -31
  207. data/guides/rails_guides/textile_extensions.rb +0 -63
  208. data/guides/rails_guides.rb +0 -50
  209. data/guides/source/2_2_release_notes.textile +0 -422
  210. data/guides/source/2_3_release_notes.textile +0 -610
  211. data/guides/source/3_0_release_notes.textile +0 -595
  212. data/guides/source/3_1_release_notes.textile +0 -553
  213. data/guides/source/3_2_release_notes.textile +0 -540
  214. data/guides/source/_license.html.erb +0 -2
  215. data/guides/source/_welcome.html.erb +0 -19
  216. data/guides/source/action_controller_overview.textile +0 -820
  217. data/guides/source/action_mailer_basics.textile +0 -516
  218. data/guides/source/action_view_overview.textile +0 -1497
  219. data/guides/source/active_model_basics.textile +0 -205
  220. data/guides/source/active_record_basics.textile +0 -218
  221. data/guides/source/active_record_querying.textile +0 -1433
  222. data/guides/source/active_record_validations_callbacks.textile +0 -1283
  223. data/guides/source/active_resource_basics.textile +0 -120
  224. data/guides/source/active_support_core_extensions.textile +0 -3713
  225. data/guides/source/ajax_on_rails.textile +0 -267
  226. data/guides/source/api_documentation_guidelines.textile +0 -185
  227. data/guides/source/asset_pipeline.textile +0 -707
  228. data/guides/source/association_basics.textile +0 -1959
  229. data/guides/source/caching_with_rails.textile +0 -437
  230. data/guides/source/command_line.textile +0 -574
  231. data/guides/source/configuring.textile +0 -641
  232. data/guides/source/contributing_to_ruby_on_rails.textile +0 -448
  233. data/guides/source/credits.html.erb +0 -72
  234. data/guides/source/debugging_rails_applications.textile +0 -714
  235. data/guides/source/documents.yaml +0 -157
  236. data/guides/source/engines.textile +0 -618
  237. data/guides/source/form_helpers.textile +0 -798
  238. data/guides/source/generators.textile +0 -621
  239. data/guides/source/getting_started.textile +0 -1929
  240. data/guides/source/i18n.textile +0 -931
  241. data/guides/source/index.html.erb +0 -30
  242. data/guides/source/initialization.textile +0 -1116
  243. data/guides/source/kindle/KINDLE.md +0 -26
  244. data/guides/source/kindle/copyright.html.erb +0 -1
  245. data/guides/source/kindle/layout.html.erb +0 -27
  246. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  247. data/guides/source/kindle/toc.html.erb +0 -24
  248. data/guides/source/kindle/toc.ncx.erb +0 -64
  249. data/guides/source/kindle/welcome.html.erb +0 -5
  250. data/guides/source/layout.html.erb +0 -124
  251. data/guides/source/layouts_and_rendering.textile +0 -1237
  252. data/guides/source/migrations.textile +0 -900
  253. data/guides/source/nested_model_forms.textile +0 -222
  254. data/guides/source/performance_testing.textile +0 -597
  255. data/guides/source/plugins.textile +0 -464
  256. data/guides/source/rails_application_templates.textile +0 -240
  257. data/guides/source/rails_on_rack.textile +0 -236
  258. data/guides/source/routing.textile +0 -885
  259. data/guides/source/ruby_on_rails_guides_guidelines.textile +0 -79
  260. data/guides/source/security.textile +0 -1004
  261. data/guides/source/testing.textile +0 -947
  262. data/guides/w3c_validator.rb +0 -91
  263. data/lib/rails/all.rb +0 -15
  264. data/lib/rails/application/bootstrap.rb +0 -73
  265. data/lib/rails/application/configuration.rb +0 -151
  266. data/lib/rails/application/finisher.rb +0 -98
  267. data/lib/rails/application/railties.rb +0 -13
  268. data/lib/rails/application/route_inspector.rb +0 -84
  269. data/lib/rails/application/routes_reloader.rb +0 -56
  270. data/lib/rails/application.rb +0 -320
  271. data/lib/rails/backtrace_cleaner.rb +0 -42
  272. data/lib/rails/cli.rb +0 -16
  273. data/lib/rails/code_statistics.rb +0 -118
  274. data/lib/rails/commands/application.rb +0 -36
  275. data/lib/rails/commands/benchmarker.rb +0 -34
  276. data/lib/rails/commands/console.rb +0 -55
  277. data/lib/rails/commands/dbconsole.rb +0 -123
  278. data/lib/rails/commands/destroy.rb +0 -10
  279. data/lib/rails/commands/generate.rb +0 -12
  280. data/lib/rails/commands/plugin.rb +0 -544
  281. data/lib/rails/commands/plugin_new.rb +0 -11
  282. data/lib/rails/commands/profiler.rb +0 -32
  283. data/lib/rails/commands/runner.rb +0 -54
  284. data/lib/rails/commands/server.rb +0 -100
  285. data/lib/rails/commands/update.rb +0 -9
  286. data/lib/rails/commands.rb +0 -104
  287. data/lib/rails/configuration.rb +0 -89
  288. data/lib/rails/console/app.rb +0 -36
  289. data/lib/rails/console/helpers.rb +0 -11
  290. data/lib/rails/engine/commands.rb +0 -43
  291. data/lib/rails/engine/configuration.rb +0 -84
  292. data/lib/rails/engine/railties.rb +0 -33
  293. data/lib/rails/engine.rb +0 -657
  294. data/lib/rails/generators/actions.rb +0 -325
  295. data/lib/rails/generators/active_model.rb +0 -78
  296. data/lib/rails/generators/app_base.rb +0 -266
  297. data/lib/rails/generators/base.rb +0 -390
  298. data/lib/rails/generators/css/assets/assets_generator.rb +0 -13
  299. data/lib/rails/generators/css/assets/templates/stylesheet.css +0 -4
  300. data/lib/rails/generators/css/scaffold/scaffold_generator.rb +0 -16
  301. data/lib/rails/generators/erb/controller/controller_generator.rb +0 -20
  302. data/lib/rails/generators/erb/controller/templates/view.html.erb +0 -2
  303. data/lib/rails/generators/erb/mailer/mailer_generator.rb +0 -13
  304. data/lib/rails/generators/erb/mailer/templates/view.text.erb +0 -3
  305. data/lib/rails/generators/erb/scaffold/scaffold_generator.rb +0 -29
  306. data/lib/rails/generators/erb/scaffold/templates/_form.html.erb +0 -23
  307. data/lib/rails/generators/erb/scaffold/templates/edit.html.erb +0 -6
  308. data/lib/rails/generators/erb/scaffold/templates/index.html.erb +0 -27
  309. data/lib/rails/generators/erb/scaffold/templates/new.html.erb +0 -5
  310. data/lib/rails/generators/erb/scaffold/templates/show.html.erb +0 -12
  311. data/lib/rails/generators/erb.rb +0 -21
  312. data/lib/rails/generators/generated_attribute.rb +0 -107
  313. data/lib/rails/generators/js/assets/assets_generator.rb +0 -13
  314. data/lib/rails/generators/js/assets/templates/javascript.js +0 -2
  315. data/lib/rails/generators/migration.rb +0 -68
  316. data/lib/rails/generators/named_base.rb +0 -202
  317. data/lib/rails/generators/rails/app/USAGE +0 -15
  318. data/lib/rails/generators/rails/app/app_generator.rb +0 -312
  319. data/lib/rails/generators/rails/app/templates/Gemfile +0 -21
  320. data/lib/rails/generators/rails/app/templates/README +0 -261
  321. data/lib/rails/generators/rails/app/templates/Rakefile +0 -7
  322. data/lib/rails/generators/rails/app/templates/app/assets/images/rails.png +0 -0
  323. data/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt +0 -17
  324. data/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css +0 -13
  325. data/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb +0 -3
  326. data/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb +0 -2
  327. data/lib/rails/generators/rails/app/templates/app/mailers/.empty_directory +0 -0
  328. data/lib/rails/generators/rails/app/templates/app/models/.empty_directory +0 -0
  329. data/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt +0 -14
  330. data/lib/rails/generators/rails/app/templates/config/application.rb +0 -68
  331. data/lib/rails/generators/rails/app/templates/config/boot.rb +0 -6
  332. data/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml +0 -31
  333. data/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml +0 -86
  334. data/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml +0 -62
  335. data/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml +0 -33
  336. data/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml +0 -43
  337. data/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml +0 -20
  338. data/lib/rails/generators/rails/app/templates/config/databases/mysql.yml +0 -54
  339. data/lib/rails/generators/rails/app/templates/config/databases/oracle.yml +0 -39
  340. data/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +0 -55
  341. data/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml +0 -25
  342. data/lib/rails/generators/rails/app/templates/config/environment.rb +0 -5
  343. data/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt +0 -41
  344. data/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +0 -73
  345. data/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +0 -39
  346. data/lib/rails/generators/rails/app/templates/config/initializers/backtrace_silencers.rb +0 -7
  347. data/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb +0 -15
  348. data/lib/rails/generators/rails/app/templates/config/initializers/mime_types.rb +0 -5
  349. data/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt +0 -7
  350. data/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt +0 -8
  351. data/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt +0 -16
  352. data/lib/rails/generators/rails/app/templates/config/locales/en.yml +0 -5
  353. data/lib/rails/generators/rails/app/templates/config/routes.rb +0 -58
  354. data/lib/rails/generators/rails/app/templates/config.ru +0 -4
  355. data/lib/rails/generators/rails/app/templates/db/seeds.rb.tt +0 -7
  356. data/lib/rails/generators/rails/app/templates/doc/README_FOR_APP +0 -2
  357. data/lib/rails/generators/rails/app/templates/gitignore +0 -15
  358. data/lib/rails/generators/rails/app/templates/public/404.html +0 -26
  359. data/lib/rails/generators/rails/app/templates/public/422.html +0 -26
  360. data/lib/rails/generators/rails/app/templates/public/500.html +0 -25
  361. data/lib/rails/generators/rails/app/templates/public/robots.txt +0 -5
  362. data/lib/rails/generators/rails/app/templates/public/stylesheets/.empty_directory +0 -0
  363. data/lib/rails/generators/rails/app/templates/script/openskies +0 -5
  364. data/lib/rails/generators/rails/app/templates/test/fixtures/.empty_directory +0 -0
  365. data/lib/rails/generators/rails/app/templates/test/functional/.empty_directory +0 -0
  366. data/lib/rails/generators/rails/app/templates/test/integration/.empty_directory +0 -0
  367. data/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb +0 -12
  368. data/lib/rails/generators/rails/app/templates/test/test_helper.rb +0 -15
  369. data/lib/rails/generators/rails/app/templates/test/unit/.empty_directory +0 -0
  370. data/lib/rails/generators/rails/assets/USAGE +0 -20
  371. data/lib/rails/generators/rails/assets/assets_generator.rb +0 -25
  372. data/lib/rails/generators/rails/assets/templates/javascript.js +0 -2
  373. data/lib/rails/generators/rails/assets/templates/stylesheet.css +0 -4
  374. data/lib/rails/generators/rails/controller/USAGE +0 -18
  375. data/lib/rails/generators/rails/controller/controller_generator.rb +0 -20
  376. data/lib/rails/generators/rails/controller/templates/controller.rb +0 -13
  377. data/lib/rails/generators/rails/generator/USAGE +0 -12
  378. data/lib/rails/generators/rails/generator/generator_generator.rb +0 -25
  379. data/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt +0 -3
  380. data/lib/rails/generators/rails/generator/templates/USAGE.tt +0 -8
  381. data/lib/rails/generators/rails/generator/templates/templates/.empty_directory +0 -0
  382. data/lib/rails/generators/rails/helper/USAGE +0 -17
  383. data/lib/rails/generators/rails/helper/helper_generator.rb +0 -13
  384. data/lib/rails/generators/rails/helper/templates/helper.rb +0 -4
  385. data/lib/rails/generators/rails/integration_test/USAGE +0 -10
  386. data/lib/rails/generators/rails/integration_test/integration_test_generator.rb +0 -7
  387. data/lib/rails/generators/rails/migration/USAGE +0 -29
  388. data/lib/rails/generators/rails/migration/migration_generator.rb +0 -8
  389. data/lib/rails/generators/rails/model/USAGE +0 -45
  390. data/lib/rails/generators/rails/model/model_generator.rb +0 -8
  391. data/lib/rails/generators/rails/observer/USAGE +0 -12
  392. data/lib/rails/generators/rails/observer/observer_generator.rb +0 -7
  393. data/lib/rails/generators/rails/performance_test/USAGE +0 -10
  394. data/lib/rails/generators/rails/performance_test/performance_test_generator.rb +0 -7
  395. data/lib/rails/generators/rails/plugin_new/USAGE +0 -10
  396. data/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb +0 -318
  397. data/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec +0 -29
  398. data/lib/rails/generators/rails/plugin_new/templates/Gemfile +0 -23
  399. data/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE +0 -20
  400. data/lib/rails/generators/rails/plugin_new/templates/README.rdoc +0 -3
  401. data/lib/rails/generators/rails/plugin_new/templates/Rakefile +0 -31
  402. data/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt +0 -4
  403. data/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt +0 -4
  404. data/lib/rails/generators/rails/plugin_new/templates/app/mailers/.empty_directory +0 -0
  405. data/lib/rails/generators/rails/plugin_new/templates/app/models/.empty_directory +0 -0
  406. data/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt +0 -14
  407. data/lib/rails/generators/rails/plugin_new/templates/config/routes.rb +0 -6
  408. data/lib/rails/generators/rails/plugin_new/templates/gitignore +0 -7
  409. data/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb +0 -7
  410. data/lib/rails/generators/rails/plugin_new/templates/lib/%name%/version.rb +0 -3
  411. data/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb +0 -6
  412. data/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake +0 -4
  413. data/lib/rails/generators/rails/plugin_new/templates/rails/application.rb +0 -18
  414. data/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb +0 -10
  415. data/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb +0 -4
  416. data/lib/rails/generators/rails/plugin_new/templates/script/rails.tt +0 -7
  417. data/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb +0 -7
  418. data/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb +0 -12
  419. data/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb +0 -15
  420. data/lib/rails/generators/rails/resource/USAGE +0 -23
  421. data/lib/rails/generators/rails/resource/resource_generator.rb +0 -20
  422. data/lib/rails/generators/rails/resource_route/resource_route_generator.rb +0 -50
  423. data/lib/rails/generators/rails/scaffold/USAGE +0 -35
  424. data/lib/rails/generators/rails/scaffold/scaffold_generator.rb +0 -23
  425. data/lib/rails/generators/rails/scaffold/templates/scaffold.css +0 -56
  426. data/lib/rails/generators/rails/scaffold_controller/USAGE +0 -19
  427. data/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb +0 -25
  428. data/lib/rails/generators/rails/scaffold_controller/templates/controller.rb +0 -89
  429. data/lib/rails/generators/rails/session_migration/USAGE +0 -8
  430. data/lib/rails/generators/rails/session_migration/session_migration_generator.rb +0 -8
  431. data/lib/rails/generators/rails/task/USAGE +0 -9
  432. data/lib/rails/generators/rails/task/task_generator.rb +0 -12
  433. data/lib/rails/generators/rails/task/templates/task.rb +0 -8
  434. data/lib/rails/generators/resource_helpers.rb +0 -80
  435. data/lib/rails/generators/test_case.rb +0 -247
  436. data/lib/rails/generators/test_unit/controller/controller_generator.rb +0 -15
  437. data/lib/rails/generators/test_unit/controller/templates/functional_test.rb +0 -19
  438. data/lib/rails/generators/test_unit/helper/helper_generator.rb +0 -13
  439. data/lib/rails/generators/test_unit/helper/templates/helper_test.rb +0 -6
  440. data/lib/rails/generators/test_unit/integration/integration_generator.rb +0 -13
  441. data/lib/rails/generators/test_unit/integration/templates/integration_test.rb +0 -7
  442. data/lib/rails/generators/test_unit/mailer/mailer_generator.rb +0 -14
  443. data/lib/rails/generators/test_unit/mailer/templates/functional_test.rb +0 -21
  444. data/lib/rails/generators/test_unit/model/model_generator.rb +0 -24
  445. data/lib/rails/generators/test_unit/model/templates/fixtures.yml +0 -23
  446. data/lib/rails/generators/test_unit/model/templates/unit_test.rb +0 -9
  447. data/lib/rails/generators/test_unit/observer/observer_generator.rb +0 -13
  448. data/lib/rails/generators/test_unit/observer/templates/unit_test.rb +0 -9
  449. data/lib/rails/generators/test_unit/performance/performance_generator.rb +0 -13
  450. data/lib/rails/generators/test_unit/performance/templates/performance_test.rb +0 -12
  451. data/lib/rails/generators/test_unit/plugin/plugin_generator.rb +0 -13
  452. data/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt +0 -7
  453. data/lib/rails/generators/test_unit/plugin/templates/test_helper.rb +0 -3
  454. data/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +0 -38
  455. data/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +0 -51
  456. data/lib/rails/generators/test_unit.rb +0 -8
  457. data/lib/rails/generators.rb +0 -339
  458. data/lib/rails/info.rb +0 -116
  459. data/lib/rails/info_controller.rb +0 -15
  460. data/lib/rails/initializable.rb +0 -89
  461. data/lib/rails/paths.rb +0 -211
  462. data/lib/rails/performance_test_help.rb +0 -3
  463. data/lib/rails/plugin.rb +0 -92
  464. data/lib/rails/rack/debugger.rb +0 -24
  465. data/lib/rails/rack/log_tailer.rb +0 -34
  466. data/lib/rails/rack/logger.rb +0 -60
  467. data/lib/rails/rack.rb +0 -7
  468. data/lib/rails/railtie/configurable.rb +0 -35
  469. data/lib/rails/railtie/configuration.rb +0 -90
  470. data/lib/rails/railtie.rb +0 -202
  471. data/lib/rails/ruby_version_check.rb +0 -23
  472. data/lib/rails/rubyprof_ext.rb +0 -35
  473. data/lib/rails/script_rails_loader.rb +0 -29
  474. data/lib/rails/source_annotation_extractor.rb +0 -104
  475. data/lib/rails/tasks/annotations.rake +0 -20
  476. data/lib/rails/tasks/documentation.rake +0 -155
  477. data/lib/rails/tasks/engine.rake +0 -72
  478. data/lib/rails/tasks/framework.rake +0 -76
  479. data/lib/rails/tasks/log.rake +0 -9
  480. data/lib/rails/tasks/middleware.rake +0 -7
  481. data/lib/rails/tasks/misc.rake +0 -67
  482. data/lib/rails/tasks/routes.rake +0 -9
  483. data/lib/rails/tasks/statistics.rake +0 -16
  484. data/lib/rails/tasks/tmp.rake +0 -37
  485. data/lib/rails/tasks.rb +0 -16
  486. data/lib/rails/test_help.rb +0 -56
  487. data/lib/rails/test_unit/railtie.rb +0 -15
  488. data/lib/rails/test_unit/sub_test_task.rb +0 -8
  489. data/lib/rails/test_unit/testing.rake +0 -146
  490. data/lib/rails.rb +0 -121
  491. data/lib/version.rb +0 -16
@@ -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