rails 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.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

Files changed (281) hide show
  1. checksums.yaml +4 -4
  2. data/README.rdoc +77 -0
  3. data/guides/CHANGELOG.md +9 -0
  4. data/guides/Rakefile +77 -0
  5. data/guides/assets/images/belongs_to.png +0 -0
  6. data/guides/assets/images/book_icon.gif +0 -0
  7. data/guides/assets/images/bullet.gif +0 -0
  8. data/guides/assets/images/challenge.png +0 -0
  9. data/guides/assets/images/chapters_icon.gif +0 -0
  10. data/guides/assets/images/check_bullet.gif +0 -0
  11. data/guides/assets/images/credits_pic_blank.gif +0 -0
  12. data/guides/assets/images/csrf.png +0 -0
  13. data/guides/assets/images/edge_badge.png +0 -0
  14. data/guides/assets/images/favicon.ico +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/getting_started/confirm_dialog.png +0 -0
  19. data/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  20. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  21. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  22. data/guides/assets/images/getting_started/new_post.png +0 -0
  23. data/guides/assets/images/getting_started/post_with_comments.png +0 -0
  24. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  25. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  26. data/guides/assets/images/getting_started/show_action_for_posts.png +0 -0
  27. data/guides/assets/images/getting_started/template_is_missing_posts_new.png +0 -0
  28. data/guides/assets/images/getting_started/undefined_method_post_path.png +0 -0
  29. data/guides/assets/images/getting_started/unknown_action_create_for_posts.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_new_for_posts.png +0 -0
  31. data/guides/assets/images/grey_bullet.gif +0 -0
  32. data/guides/assets/images/habtm.png +0 -0
  33. data/guides/assets/images/has_many.png +0 -0
  34. data/guides/assets/images/has_many_through.png +0 -0
  35. data/guides/assets/images/has_one.png +0 -0
  36. data/guides/assets/images/has_one_through.png +0 -0
  37. data/guides/assets/images/header_backdrop.png +0 -0
  38. data/guides/assets/images/header_tile.gif +0 -0
  39. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  40. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  41. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  44. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  45. data/guides/assets/images/icons/README +5 -0
  46. data/guides/assets/images/icons/callouts/1.png +0 -0
  47. data/guides/assets/images/icons/callouts/10.png +0 -0
  48. data/guides/assets/images/icons/callouts/11.png +0 -0
  49. data/guides/assets/images/icons/callouts/12.png +0 -0
  50. data/guides/assets/images/icons/callouts/13.png +0 -0
  51. data/guides/assets/images/icons/callouts/14.png +0 -0
  52. data/guides/assets/images/icons/callouts/15.png +0 -0
  53. data/guides/assets/images/icons/callouts/2.png +0 -0
  54. data/guides/assets/images/icons/callouts/3.png +0 -0
  55. data/guides/assets/images/icons/callouts/4.png +0 -0
  56. data/guides/assets/images/icons/callouts/5.png +0 -0
  57. data/guides/assets/images/icons/callouts/6.png +0 -0
  58. data/guides/assets/images/icons/callouts/7.png +0 -0
  59. data/guides/assets/images/icons/callouts/8.png +0 -0
  60. data/guides/assets/images/icons/callouts/9.png +0 -0
  61. data/guides/assets/images/icons/caution.png +0 -0
  62. data/guides/assets/images/icons/example.png +0 -0
  63. data/guides/assets/images/icons/home.png +0 -0
  64. data/guides/assets/images/icons/important.png +0 -0
  65. data/guides/assets/images/icons/next.png +0 -0
  66. data/guides/assets/images/icons/note.png +0 -0
  67. data/guides/assets/images/icons/prev.png +0 -0
  68. data/guides/assets/images/icons/tip.png +0 -0
  69. data/guides/assets/images/icons/up.png +0 -0
  70. data/guides/assets/images/icons/warning.png +0 -0
  71. data/guides/assets/images/jaimeiniesta.jpg +0 -0
  72. data/guides/assets/images/nav_arrow.gif +0 -0
  73. data/guides/assets/images/oscardelben.jpg +0 -0
  74. data/guides/assets/images/polymorphic.png +0 -0
  75. data/guides/assets/images/radar.png +0 -0
  76. data/guides/assets/images/rails4_features.png +0 -0
  77. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  78. data/guides/assets/images/rails_guides_logo.gif +0 -0
  79. data/guides/assets/images/rails_logo_remix.gif +0 -0
  80. data/guides/assets/images/rails_welcome.png +0 -0
  81. data/guides/assets/images/session_fixation.png +0 -0
  82. data/guides/assets/images/tab_grey.gif +0 -0
  83. data/guides/assets/images/tab_info.gif +0 -0
  84. data/guides/assets/images/tab_note.gif +0 -0
  85. data/guides/assets/images/tab_red.gif +0 -0
  86. data/guides/assets/images/tab_yellow.gif +0 -0
  87. data/guides/assets/images/tab_yellow.png +0 -0
  88. data/guides/assets/images/vijaydev.jpg +0 -0
  89. data/guides/assets/javascripts/guides.js +57 -0
  90. data/guides/assets/javascripts/jquery.min.js +4 -0
  91. data/guides/assets/javascripts/responsive-tables.js +43 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  118. data/guides/assets/stylesheets/fixes.css +16 -0
  119. data/guides/assets/stylesheets/kindle.css +11 -0
  120. data/guides/assets/stylesheets/main.css +709 -0
  121. data/guides/assets/stylesheets/print.css +52 -0
  122. data/guides/assets/stylesheets/reset.css +43 -0
  123. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  124. data/guides/assets/stylesheets/style.css +13 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  143. data/guides/code/getting_started/Gemfile +38 -0
  144. data/guides/code/getting_started/Gemfile.lock +150 -0
  145. data/guides/code/getting_started/README.rdoc +28 -0
  146. data/guides/code/getting_started/Rakefile +6 -0
  147. data/guides/code/getting_started/app/assets/images/rails.png +0 -0
  148. data/guides/code/getting_started/app/assets/javascripts/application.js +16 -0
  149. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +3 -0
  150. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +3 -0
  151. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +3 -0
  152. data/guides/code/getting_started/app/assets/stylesheets/application.css +13 -0
  153. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +3 -0
  154. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +3 -0
  155. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +3 -0
  156. data/guides/code/getting_started/app/controllers/application_controller.rb +5 -0
  157. data/guides/code/getting_started/app/controllers/comments_controller.rb +17 -0
  158. data/guides/code/getting_started/app/controllers/posts_controller.rb +47 -0
  159. data/guides/code/getting_started/app/controllers/welcome_controller.rb +4 -0
  160. data/guides/code/getting_started/app/helpers/application_helper.rb +2 -0
  161. data/guides/code/getting_started/app/helpers/comments_helper.rb +2 -0
  162. data/guides/code/getting_started/app/helpers/posts_helper.rb +2 -0
  163. data/guides/code/getting_started/app/helpers/welcome_helper.rb +2 -0
  164. data/guides/code/getting_started/app/models/comment.rb +3 -0
  165. data/guides/code/getting_started/app/models/post.rb +7 -0
  166. data/guides/code/getting_started/app/views/comments/_comment.html.erb +15 -0
  167. data/guides/code/getting_started/app/views/comments/_form.html.erb +13 -0
  168. data/guides/code/getting_started/app/views/layouts/application.html.erb +14 -0
  169. data/guides/code/getting_started/app/views/posts/_form.html.erb +27 -0
  170. data/guides/code/getting_started/app/views/posts/edit.html.erb +5 -0
  171. data/guides/code/getting_started/app/views/posts/index.html.erb +21 -0
  172. data/guides/code/getting_started/app/views/posts/new.html.erb +5 -0
  173. data/guides/code/getting_started/app/views/posts/show.html.erb +18 -0
  174. data/guides/code/getting_started/app/views/welcome/index.html.erb +3 -0
  175. data/guides/code/getting_started/bin/bundle +4 -0
  176. data/guides/code/getting_started/bin/rails +4 -0
  177. data/guides/code/getting_started/bin/rake +4 -0
  178. data/guides/code/getting_started/config.ru +4 -0
  179. data/guides/code/getting_started/config/application.rb +17 -0
  180. data/guides/code/getting_started/config/boot.rb +4 -0
  181. data/guides/code/getting_started/config/database.yml +25 -0
  182. data/guides/code/getting_started/config/environment.rb +5 -0
  183. data/guides/code/getting_started/config/environments/development.rb +30 -0
  184. data/guides/code/getting_started/config/environments/production.rb +80 -0
  185. data/guides/code/getting_started/config/environments/test.rb +36 -0
  186. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +7 -0
  187. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +4 -0
  188. data/guides/code/getting_started/config/initializers/inflections.rb +16 -0
  189. data/guides/code/getting_started/config/initializers/locale.rb +9 -0
  190. data/guides/code/getting_started/config/initializers/mime_types.rb +5 -0
  191. data/guides/code/getting_started/config/initializers/secret_token.rb +12 -0
  192. data/guides/code/getting_started/config/initializers/session_store.rb +3 -0
  193. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +14 -0
  194. data/guides/code/getting_started/config/locales/en.yml +23 -0
  195. data/guides/code/getting_started/config/routes.rb +7 -0
  196. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +10 -0
  197. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +11 -0
  198. data/guides/code/getting_started/db/schema.rb +33 -0
  199. data/guides/code/getting_started/db/seeds.rb +7 -0
  200. data/guides/code/getting_started/public/404.html +27 -0
  201. data/guides/code/getting_started/public/422.html +26 -0
  202. data/guides/code/getting_started/public/500.html +26 -0
  203. data/guides/code/getting_started/public/favicon.ico +0 -0
  204. data/guides/code/getting_started/public/robots.txt +5 -0
  205. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +7 -0
  206. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +7 -0
  207. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +9 -0
  208. data/guides/code/getting_started/test/fixtures/comments.yml +11 -0
  209. data/guides/code/getting_started/test/fixtures/posts.yml +9 -0
  210. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +4 -0
  211. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +4 -0
  212. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +4 -0
  213. data/guides/code/getting_started/test/models/comment_test.rb +7 -0
  214. data/guides/code/getting_started/test/models/post_test.rb +7 -0
  215. data/guides/code/getting_started/test/test_helper.rb +15 -0
  216. data/guides/rails_guides.rb +44 -0
  217. data/guides/rails_guides/generator.rb +248 -0
  218. data/guides/rails_guides/helpers.rb +51 -0
  219. data/guides/rails_guides/indexer.rb +68 -0
  220. data/guides/rails_guides/kindle.rb +119 -0
  221. data/guides/rails_guides/levenshtein.rb +31 -0
  222. data/guides/rails_guides/markdown.rb +163 -0
  223. data/guides/rails_guides/markdown/renderer.rb +82 -0
  224. data/guides/source/2_2_release_notes.md +435 -0
  225. data/guides/source/2_3_release_notes.md +621 -0
  226. data/guides/source/3_0_release_notes.md +614 -0
  227. data/guides/source/3_1_release_notes.md +556 -0
  228. data/guides/source/3_2_release_notes.md +565 -0
  229. data/guides/source/4_0_release_notes.md +228 -0
  230. data/guides/source/_license.html.erb +2 -0
  231. data/guides/source/_welcome.html.erb +19 -0
  232. data/guides/source/action_controller_overview.md +872 -0
  233. data/guides/source/action_mailer_basics.md +599 -0
  234. data/guides/source/action_view_overview.md +1565 -0
  235. data/guides/source/active_model_basics.md +200 -0
  236. data/guides/source/active_record_basics.md +370 -0
  237. data/guides/source/active_record_callbacks.md +358 -0
  238. data/guides/source/active_record_querying.md +1621 -0
  239. data/guides/source/active_record_validations.md +1128 -0
  240. data/guides/source/active_support_core_extensions.md +3791 -0
  241. data/guides/source/active_support_instrumentation.md +487 -0
  242. data/guides/source/api_documentation_guidelines.md +209 -0
  243. data/guides/source/asset_pipeline.md +832 -0
  244. data/guides/source/association_basics.md +2129 -0
  245. data/guides/source/caching_with_rails.md +350 -0
  246. data/guides/source/command_line.md +594 -0
  247. data/guides/source/configuring.md +736 -0
  248. data/guides/source/contributing_to_ruby_on_rails.md +455 -0
  249. data/guides/source/credits.html.erb +76 -0
  250. data/guides/source/debugging_rails_applications.md +675 -0
  251. data/guides/source/development_dependencies_install.md +195 -0
  252. data/guides/source/documents.yaml +179 -0
  253. data/guides/source/engines.md +961 -0
  254. data/guides/source/form_helpers.md +955 -0
  255. data/guides/source/generators.md +644 -0
  256. data/guides/source/getting_started.md +1775 -0
  257. data/guides/source/i18n.md +983 -0
  258. data/guides/source/index.html.erb +27 -0
  259. data/guides/source/initialization.md +562 -0
  260. data/guides/source/kindle/KINDLE.md +26 -0
  261. data/guides/source/kindle/copyright.html.erb +1 -0
  262. data/guides/source/kindle/layout.html.erb +27 -0
  263. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  264. data/guides/source/kindle/toc.html.erb +24 -0
  265. data/guides/source/kindle/toc.ncx.erb +64 -0
  266. data/guides/source/kindle/welcome.html.erb +5 -0
  267. data/guides/source/layout.html.erb +148 -0
  268. data/guides/source/layouts_and_rendering.md +1132 -0
  269. data/guides/source/migrations.md +1059 -0
  270. data/guides/source/nested_model_forms.md +225 -0
  271. data/guides/source/plugins.md +435 -0
  272. data/guides/source/rails_application_templates.md +229 -0
  273. data/guides/source/rails_on_rack.md +342 -0
  274. data/guides/source/routing.md +1088 -0
  275. data/guides/source/ruby_on_rails_guides_guidelines.md +124 -0
  276. data/guides/source/security.md +973 -0
  277. data/guides/source/testing.md +981 -0
  278. data/guides/source/upgrading_ruby_on_rails.md +286 -0
  279. data/guides/source/working_with_javascript_in_rails.md +396 -0
  280. data/guides/w3c_validator.rb +95 -0
  281. metadata +315 -31
@@ -0,0 +1,358 @@
1
+ Active Record Callbacks
2
+ =======================
3
+
4
+ This guide teaches you how to hook into the life cycle of your Active Record
5
+ objects.
6
+
7
+ After reading this guide, you will know:
8
+
9
+ * The life cycle of Active Record objects.
10
+ * How to create callback methods that respond to events in the object life cycle.
11
+ * How to create special classes that encapsulate common behavior for your callbacks.
12
+
13
+ --------------------------------------------------------------------------------
14
+
15
+ The Object Life Cycle
16
+ ---------------------
17
+
18
+ During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object life cycle</em> so that you can control your application and its data.
19
+
20
+ Callbacks allow you to trigger logic before or after an alteration of an object's state.
21
+
22
+ Callbacks Overview
23
+ ------------------
24
+
25
+ Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
26
+
27
+ ### Callback Registration
28
+
29
+ In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks:
30
+
31
+ ```ruby
32
+ class User < ActiveRecord::Base
33
+ validates :login, :email, presence: true
34
+
35
+ before_validation :ensure_login_has_a_value
36
+
37
+ protected
38
+ def ensure_login_has_a_value
39
+ if login.nil?
40
+ self.login = email unless email.blank?
41
+ end
42
+ end
43
+ end
44
+ ```
45
+
46
+ The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in a single line:
47
+
48
+ ```ruby
49
+ class User < ActiveRecord::Base
50
+ validates :login, :email, presence: true
51
+
52
+ before_create do |user|
53
+ user.name = user.login.capitalize if user.name.blank?
54
+ end
55
+ end
56
+ ```
57
+
58
+ Callbacks can also be registered to only fire on certain lifecycle events:
59
+
60
+ ```ruby
61
+ class User < ActiveRecord::Base
62
+ before_validation :normalize_name, on: :create
63
+
64
+ # :on takes an array as well
65
+ after_validation :set_location, on: [ :create, :update ]
66
+
67
+ protected
68
+ def normalize_name
69
+ self.name = self.name.downcase.titleize
70
+ end
71
+
72
+ def set_location
73
+ self.location = LocationService.query(self)
74
+ end
75
+ end
76
+ ```
77
+
78
+ It is considered good practice to declare callback methods as protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.
79
+
80
+ Available Callbacks
81
+ -------------------
82
+
83
+ Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations:
84
+
85
+ ### Creating an Object
86
+
87
+ * `before_validation`
88
+ * `after_validation`
89
+ * `before_save`
90
+ * `around_save`
91
+ * `before_create`
92
+ * `around_create`
93
+ * `after_create`
94
+ * `after_save`
95
+
96
+ ### Updating an Object
97
+
98
+ * `before_validation`
99
+ * `after_validation`
100
+ * `before_save`
101
+ * `around_save`
102
+ * `before_update`
103
+ * `around_update`
104
+ * `after_update`
105
+ * `after_save`
106
+
107
+ ### Destroying an Object
108
+
109
+ * `before_destroy`
110
+ * `around_destroy`
111
+ * `after_destroy`
112
+
113
+ WARNING. `after_save` runs both on create and update, but always _after_ the more specific callbacks `after_create` and `after_update`, no matter the order in which the macro calls were executed.
114
+
115
+ ### `after_initialize` and `after_find`
116
+
117
+ The `after_initialize` callback will be called whenever an Active Record object is instantiated, either by directly using `new` or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record `initialize` method.
118
+
119
+ The `after_find` callback will be called whenever Active Record loads a record from the database. `after_find` is called before `after_initialize` if both are defined.
120
+
121
+ The `after_initialize` and `after_find` callbacks have no `before_*` counterparts, but they can be registered just like the other Active Record callbacks.
122
+
123
+ ```ruby
124
+ class User < ActiveRecord::Base
125
+ after_initialize do |user|
126
+ puts "You have initialized an object!"
127
+ end
128
+
129
+ after_find do |user|
130
+ puts "You have found an object!"
131
+ end
132
+ end
133
+
134
+ >> User.new
135
+ You have initialized an object!
136
+ => #<User id: nil>
137
+
138
+ >> User.first
139
+ You have found an object!
140
+ You have initialized an object!
141
+ => #<User id: 1>
142
+ ```
143
+
144
+ Running Callbacks
145
+ -----------------
146
+
147
+ The following methods trigger callbacks:
148
+
149
+ * `create`
150
+ * `create!`
151
+ * `decrement!`
152
+ * `destroy`
153
+ * `destroy!`
154
+ * `destroy_all`
155
+ * `increment!`
156
+ * `save`
157
+ * `save!`
158
+ * `save(validate: false)`
159
+ * `toggle!`
160
+ * `update_attribute`
161
+ * `update`
162
+ * `update!`
163
+ * `valid?`
164
+
165
+ Additionally, the `after_find` callback is triggered by the following finder methods:
166
+
167
+ * `all`
168
+ * `first`
169
+ * `find`
170
+ * `find_by_*`
171
+ * `find_by_*!`
172
+ * `find_by_sql`
173
+ * `last`
174
+
175
+ The `after_initialize` callback is triggered every time a new object of the class is initialized.
176
+
177
+ NOTE: The `find_by_*` and `find_by_*!` methods are dynamic finders generated automatically for every attribute. Learn more about them at the [Dynamic finders section](active_record_querying.html#dynamic-finders)
178
+
179
+ Skipping Callbacks
180
+ ------------------
181
+
182
+ Just as with validations, it is also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
183
+
184
+ * `decrement`
185
+ * `decrement_counter`
186
+ * `delete`
187
+ * `delete_all`
188
+ * `increment`
189
+ * `increment_counter`
190
+ * `toggle`
191
+ * `touch`
192
+ * `update_column`
193
+ * `update_columns`
194
+ * `update_all`
195
+ * `update_counters`
196
+
197
+ Halting Execution
198
+ -----------------
199
+
200
+ As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
201
+
202
+ The whole callback chain is wrapped in a transaction. If any _before_ callback method returns exactly `false` or raises an exception, the execution chain gets halted and a ROLLBACK is issued; _after_ callbacks can only accomplish that by raising an exception.
203
+
204
+ WARNING. Raising an arbitrary exception may break code that expects `save` and its friends not to fail like that. The `ActiveRecord::Rollback` exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised.
205
+
206
+ Relational Callbacks
207
+ --------------------
208
+
209
+ Callbacks work through model relationships, and can even be defined by them. Suppose an example where a user has many posts. A user's posts should be destroyed if the user is destroyed. Let's add an `after_destroy` callback to the `User` model by way of its relationship to the `Post` model:
210
+
211
+ ```ruby
212
+ class User < ActiveRecord::Base
213
+ has_many :posts, dependent: :destroy
214
+ end
215
+
216
+ class Post < ActiveRecord::Base
217
+ after_destroy :log_destroy_action
218
+
219
+ def log_destroy_action
220
+ puts 'Post destroyed'
221
+ end
222
+ end
223
+
224
+ >> user = User.first
225
+ => #<User id: 1>
226
+ >> user.posts.create!
227
+ => #<Post id: 1, user_id: 1>
228
+ >> user.destroy
229
+ Post destroyed
230
+ => #<User id: 1>
231
+ ```
232
+
233
+ Conditional Callbacks
234
+ ---------------------
235
+
236
+ As with validations, we can also make the calling of a callback method conditional on the satisfaction of a given predicate. We can do this using the `:if` and `:unless` options, which can take a symbol, a string, a `Proc` or an `Array`. You may use the `:if` option when you want to specify under which conditions the callback **should** be called. If you want to specify the conditions under which the callback **should not** be called, then you may use the `:unless` option.
237
+
238
+ ### Using `:if` and `:unless` with a `Symbol`
239
+
240
+ You can associate the `:if` and `:unless` options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the `:if` option, the callback won't be executed if the predicate method returns false; when using the `:unless` option, the callback won't be executed if the predicate method returns true. This is the most common option. Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed.
241
+
242
+ ```ruby
243
+ class Order < ActiveRecord::Base
244
+ before_save :normalize_card_number, if: :paid_with_card?
245
+ end
246
+ ```
247
+
248
+ ### Using `:if` and `:unless` with a String
249
+
250
+ You can also use a string that will be evaluated using `eval` and hence needs to contain valid Ruby code. You should use this option only when the string represents a really short condition:
251
+
252
+ ```ruby
253
+ class Order < ActiveRecord::Base
254
+ before_save :normalize_card_number, if: "paid_with_card?"
255
+ end
256
+ ```
257
+
258
+ ### Using `:if` and `:unless` with a `Proc`
259
+
260
+ Finally, it is possible to associate `:if` and `:unless` with a `Proc` object. This option is best suited when writing short validation methods, usually one-liners:
261
+
262
+ ```ruby
263
+ class Order < ActiveRecord::Base
264
+ before_save :normalize_card_number,
265
+ if: Proc.new { |order| order.paid_with_card? }
266
+ end
267
+ ```
268
+
269
+ ### Multiple Conditions for Callbacks
270
+
271
+ When writing conditional callbacks, it is possible to mix both `:if` and `:unless` in the same callback declaration:
272
+
273
+ ```ruby
274
+ class Comment < ActiveRecord::Base
275
+ after_create :send_email_to_author, if: :author_wants_emails?,
276
+ unless: Proc.new { |comment| comment.post.ignore_comments? }
277
+ end
278
+ ```
279
+
280
+ Callback Classes
281
+ ----------------
282
+
283
+ Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
284
+
285
+ Here's an example where we create a class with an `after_destroy` callback for a `PictureFile` model:
286
+
287
+ ```ruby
288
+ class PictureFileCallbacks
289
+ def after_destroy(picture_file)
290
+ if File.exists?(picture_file.filepath)
291
+ File.delete(picture_file.filepath)
292
+ end
293
+ end
294
+ end
295
+ ```
296
+
297
+ When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:
298
+
299
+ ```ruby
300
+ class PictureFile < ActiveRecord::Base
301
+ after_destroy PictureFileCallbacks.new
302
+ end
303
+ ```
304
+
305
+ Note that we needed to instantiate a new `PictureFileCallbacks` object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of the instantiated object. Often, however, it will make more sense to declare the callbacks as class methods:
306
+
307
+ ```ruby
308
+ class PictureFileCallbacks
309
+ def self.after_destroy(picture_file)
310
+ if File.exists?(picture_file.filepath)
311
+ File.delete(picture_file.filepath)
312
+ end
313
+ end
314
+ end
315
+ ```
316
+
317
+ If the callback method is declared this way, it won't be necessary to instantiate a `PictureFileCallbacks` object.
318
+
319
+ ```ruby
320
+ class PictureFile < ActiveRecord::Base
321
+ after_destroy PictureFileCallbacks
322
+ end
323
+ ```
324
+
325
+ You can declare as many callbacks as you want inside your callback classes.
326
+
327
+ Transaction Callbacks
328
+ ---------------------
329
+
330
+ There are two additional callbacks that are triggered by the completion of a database transaction: `after_commit` and `after_rollback`. These callbacks are very similar to the `after_save` callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction.
331
+
332
+ Consider, for example, the previous example where the `PictureFile` model needs to delete a file after the corresponding record is destroyed. If anything raises an exception after the `after_destroy` callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that `picture_file_2` in the code below is not valid and the `save!` method raises an error.
333
+
334
+ ```ruby
335
+ PictureFile.transaction do
336
+ picture_file_1.destroy
337
+ picture_file_2.save!
338
+ end
339
+ ```
340
+
341
+ By using the `after_commit` callback we can account for this case.
342
+
343
+ ```ruby
344
+ class PictureFile < ActiveRecord::Base
345
+ after_commit :delete_picture_file_from_disk, :on => [:destroy]
346
+
347
+ def delete_picture_file_from_disk
348
+ if File.exist?(filepath)
349
+ File.delete(filepath)
350
+ end
351
+ end
352
+ end
353
+ ```
354
+
355
+ NOTE: the `:on` option specifies when a callback will be fired. If you
356
+ don't supply the `:on` option the callback will fire for every action.
357
+
358
+ The `after_commit` and `after_rollback` callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback.
@@ -0,0 +1,1621 @@
1
+ Active Record Query Interface
2
+ =============================
3
+
4
+ This guide covers different ways to retrieve data from the database using Active Record.
5
+
6
+ After reading this guide, you will know:
7
+
8
+ * How to find records using a variety of methods and conditions.
9
+ * How to specify the order, retrieved attributes, grouping, and other properties of the found records.
10
+ * How to use eager loading to reduce the number of database queries needed for data retrieval.
11
+ * How to use dynamic finders methods.
12
+ * How to check for the existence of particular records.
13
+ * How to perform various calculations on Active Record models.
14
+ * How to run EXPLAIN on relations.
15
+
16
+ --------------------------------------------------------------------------------
17
+
18
+ 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.
19
+
20
+ Code examples throughout this guide will refer to one or more of the following models:
21
+
22
+ TIP: All of the following models use `id` as the primary key, unless specified otherwise.
23
+
24
+ ```ruby
25
+ class Client < ActiveRecord::Base
26
+ has_one :address
27
+ has_many :orders
28
+ has_and_belongs_to_many :roles
29
+ end
30
+ ```
31
+
32
+ ```ruby
33
+ class Address < ActiveRecord::Base
34
+ belongs_to :client
35
+ end
36
+ ```
37
+
38
+ ```ruby
39
+ class Order < ActiveRecord::Base
40
+ belongs_to :client, counter_cache: true
41
+ end
42
+ ```
43
+
44
+ ```ruby
45
+ class Role < ActiveRecord::Base
46
+ has_and_belongs_to_many :clients
47
+ end
48
+ ```
49
+
50
+ 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.
51
+
52
+ Retrieving Objects from the Database
53
+ ------------------------------------
54
+
55
+ 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.
56
+
57
+ The methods are:
58
+
59
+ * `bind`
60
+ * `create_with`
61
+ * `eager_load`
62
+ * `extending`
63
+ * `from`
64
+ * `group`
65
+ * `having`
66
+ * `includes`
67
+ * `joins`
68
+ * `limit`
69
+ * `lock`
70
+ * `none`
71
+ * `offset`
72
+ * `order`
73
+ * `preload`
74
+ * `readonly`
75
+ * `references`
76
+ * `reorder`
77
+ * `reverse_order`
78
+ * `select`
79
+ * `uniq`
80
+ * `where`
81
+
82
+ All of the above methods return an instance of `ActiveRecord::Relation`.
83
+
84
+ The primary operation of `Model.find(options)` can be summarized as:
85
+
86
+ * Convert the supplied options to an equivalent SQL query.
87
+ * Fire the SQL query and retrieve the corresponding results from the database.
88
+ * Instantiate the equivalent Ruby object of the appropriate model for every resulting row.
89
+ * Run `after_find` callbacks, if any.
90
+
91
+ ### Retrieving a Single Object
92
+
93
+ Active Record provides five different ways of retrieving a single object.
94
+
95
+ #### Using a Primary Key
96
+
97
+ Using `Model.find(primary_key)`, you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example:
98
+
99
+ ```ruby
100
+ # Find the client with primary key (id) 10.
101
+ client = Client.find(10)
102
+ # => #<Client id: 10, first_name: "Ryan">
103
+ ```
104
+
105
+ The SQL equivalent of the above is:
106
+
107
+ ```sql
108
+ SELECT * FROM clients WHERE (clients.id = 10) LIMIT 1
109
+ ```
110
+
111
+ `Model.find(primary_key)` will raise an `ActiveRecord::RecordNotFound` exception if no matching record is found.
112
+
113
+ #### `take`
114
+
115
+ `Model.take` retrieves a record without any implicit ordering. For example:
116
+
117
+ ```ruby
118
+ client = Client.take
119
+ # => #<Client id: 1, first_name: "Lifo">
120
+ ```
121
+
122
+ The SQL equivalent of the above is:
123
+
124
+ ```sql
125
+ SELECT * FROM clients LIMIT 1
126
+ ```
127
+
128
+ `Model.take` returns `nil` if no record is found and no exception will be raised.
129
+
130
+ TIP: The retrieved record may vary depending on the database engine.
131
+
132
+ #### `first`
133
+
134
+ `Model.first` finds the first record ordered by the primary key. For example:
135
+
136
+ ```ruby
137
+ client = Client.first
138
+ # => #<Client id: 1, first_name: "Lifo">
139
+ ```
140
+
141
+ The SQL equivalent of the above is:
142
+
143
+ ```sql
144
+ SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
145
+ ```
146
+
147
+ `Model.first` returns `nil` if no matching record is found and no exception will be raised.
148
+
149
+ #### `last`
150
+
151
+ `Model.last` finds the last record ordered by the primary key. For example:
152
+
153
+ ```ruby
154
+ client = Client.last
155
+ # => #<Client id: 221, first_name: "Russel">
156
+ ```
157
+
158
+ The SQL equivalent of the above is:
159
+
160
+ ```sql
161
+ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
162
+ ```
163
+
164
+ `Model.last` returns `nil` if no matching record is found and no exception will be raised.
165
+
166
+ #### `find_by`
167
+
168
+ `Model.find_by` finds the first record matching some conditions. For example:
169
+
170
+ ```ruby
171
+ Client.find_by first_name: 'Lifo'
172
+ # => #<Client id: 1, first_name: "Lifo">
173
+
174
+ Client.find_by first_name: 'Jon'
175
+ # => nil
176
+ ```
177
+
178
+ It is equivalent to writing:
179
+
180
+ ```ruby
181
+ Client.where(first_name: 'Lifo').take
182
+ ```
183
+
184
+ #### `take!`
185
+
186
+ `Model.take!` retrieves a record without any implicit ordering. For example:
187
+
188
+ ```ruby
189
+ client = Client.take!
190
+ # => #<Client id: 1, first_name: "Lifo">
191
+ ```
192
+
193
+ The SQL equivalent of the above is:
194
+
195
+ ```sql
196
+ SELECT * FROM clients LIMIT 1
197
+ ```
198
+
199
+ `Model.take!` raises `ActiveRecord::RecordNotFound` if no matching record is found.
200
+
201
+ #### `first!`
202
+
203
+ `Model.first!` finds the first record ordered by the primary key. For example:
204
+
205
+ ```ruby
206
+ client = Client.first!
207
+ # => #<Client id: 1, first_name: "Lifo">
208
+ ```
209
+
210
+ The SQL equivalent of the above is:
211
+
212
+ ```sql
213
+ SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
214
+ ```
215
+
216
+ `Model.first!` raises `ActiveRecord::RecordNotFound` if no matching record is found.
217
+
218
+ #### `last!`
219
+
220
+ `Model.last!` finds the last record ordered by the primary key. For example:
221
+
222
+ ```ruby
223
+ client = Client.last!
224
+ # => #<Client id: 221, first_name: "Russel">
225
+ ```
226
+
227
+ The SQL equivalent of the above is:
228
+
229
+ ```sql
230
+ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
231
+ ```
232
+
233
+ `Model.last!` raises `ActiveRecord::RecordNotFound` if no matching record is found.
234
+
235
+ #### `find_by!`
236
+
237
+ `Model.find_by!` finds the first record matching some conditions. It raises `ActiveRecord::RecordNotFound` if no matching record is found. For example:
238
+
239
+ ```ruby
240
+ Client.find_by! first_name: 'Lifo'
241
+ # => #<Client id: 1, first_name: "Lifo">
242
+
243
+ Client.find_by! first_name: 'Jon'
244
+ # => ActiveRecord::RecordNotFound
245
+ ```
246
+
247
+ It is equivalent to writing:
248
+
249
+ ```ruby
250
+ Client.where(first_name: 'Lifo').take!
251
+ ```
252
+
253
+ ### Retrieving Multiple Objects
254
+
255
+ #### Using Multiple Primary Keys
256
+
257
+ `Model.find(array_of_primary_key)` accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example:
258
+
259
+ ```ruby
260
+ # Find the clients with primary keys 1 and 10.
261
+ client = Client.find([1, 10]) # Or even Client.find(1, 10)
262
+ # => [#<Client id: 1, first_name: "Lifo">, #<Client id: 10, first_name: "Ryan">]
263
+ ```
264
+
265
+ The SQL equivalent of the above is:
266
+
267
+ ```sql
268
+ SELECT * FROM clients WHERE (clients.id IN (1,10))
269
+ ```
270
+
271
+ WARNING: `Model.find(array_of_primary_key)` will raise an `ActiveRecord::RecordNotFound` exception unless a matching record is found for **all** of the supplied primary keys.
272
+
273
+ #### take
274
+
275
+ `Model.take(limit)` retrieves the first number of records specified by `limit` without any explicit ordering:
276
+
277
+ ```ruby
278
+ Client.take(2)
279
+ # => [#<Client id: 1, first_name: "Lifo">,
280
+ #<Client id: 2, first_name: "Raf">]
281
+ ```
282
+
283
+ The SQL equivalent of the above is:
284
+
285
+ ```sql
286
+ SELECT * FROM clients LIMIT 2
287
+ ```
288
+
289
+ #### first
290
+
291
+ `Model.first(limit)` finds the first number of records specified by `limit` ordered by primary key:
292
+
293
+ ```ruby
294
+ Client.first(2)
295
+ # => [#<Client id: 1, first_name: "Lifo">,
296
+ #<Client id: 2, first_name: "Raf">]
297
+ ```
298
+
299
+ The SQL equivalent of the above is:
300
+
301
+ ```sql
302
+ SELECT * FROM clients LIMIT 2
303
+ ```
304
+
305
+ #### last
306
+
307
+ `Model.last(limit)` finds the number of records specified by `limit` ordered by primary key in descending order:
308
+
309
+ ```ruby
310
+ Client.last(2)
311
+ # => [#<Client id: 10, first_name: "Ryan">,
312
+ #<Client id: 9, first_name: "John">]
313
+ ```
314
+
315
+ The SQL equivalent of the above is:
316
+
317
+ ```sql
318
+ SELECT * FROM clients ORDER By id DESC LIMIT 2
319
+ ```
320
+
321
+ ### Retrieving Multiple Objects in Batches
322
+
323
+ 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.
324
+
325
+ This may appear straightforward:
326
+
327
+ ```ruby
328
+ # This is very inefficient when the users table has thousands of rows.
329
+ User.all.each do |user|
330
+ NewsLetter.weekly_deliver(user)
331
+ end
332
+ ```
333
+
334
+ 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.
335
+
336
+ 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.
337
+
338
+ 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.
339
+
340
+ #### `find_each`
341
+
342
+ 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:
343
+
344
+ ```ruby
345
+ User.find_each do |user|
346
+ NewsLetter.weekly_deliver(user)
347
+ end
348
+ ```
349
+
350
+ ##### Options for `find_each`
351
+
352
+ 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`.
353
+
354
+ Two additional options, `:batch_size` and `:start`, are available as well.
355
+
356
+ **`:batch_size`**
357
+
358
+ 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:
359
+
360
+ ```ruby
361
+ User.find_each(batch_size: 5000) do |user|
362
+ NewsLetter.weekly_deliver(user)
363
+ end
364
+ ```
365
+
366
+ **`:start`**
367
+
368
+ 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.
369
+
370
+ For example, to send newsletters only to users with the primary key starting from 2000, and to retrieve them in batches of 5000:
371
+
372
+ ```ruby
373
+ User.find_each(start: 2000, batch_size: 5000) do |user|
374
+ NewsLetter.weekly_deliver(user)
375
+ end
376
+ ```
377
+
378
+ 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 `:start` option on each worker.
379
+
380
+ #### `find_in_batches`
381
+
382
+ 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:
383
+
384
+ ```ruby
385
+ # Give add_invoices an array of 1000 invoices at a time
386
+ Invoice.find_in_batches(include: :invoice_lines) do |invoices|
387
+ export.add_invoices(invoices)
388
+ end
389
+ ```
390
+
391
+ NOTE: The `:include` option allows you to name associations that should be loaded alongside with the models.
392
+
393
+ ##### Options for `find_in_batches`
394
+
395
+ 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`.
396
+
397
+ Conditions
398
+ ----------
399
+
400
+ 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.
401
+
402
+ ### Pure String Conditions
403
+
404
+ 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.
405
+
406
+ 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.
407
+
408
+ ### Array Conditions
409
+
410
+ Now what if that number could vary, say as an argument from somewhere? The find would then take the form:
411
+
412
+ ```ruby
413
+ Client.where("orders_count = ?", params[:orders])
414
+ ```
415
+
416
+ 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.
417
+
418
+ If you want to specify multiple conditions:
419
+
420
+ ```ruby
421
+ Client.where("orders_count = ? AND locked = ?", params[:orders], false)
422
+ ```
423
+
424
+ 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.
425
+
426
+ This code is highly preferable:
427
+
428
+ ```ruby
429
+ Client.where("orders_count = ?", params[:orders])
430
+ ```
431
+
432
+ to this code:
433
+
434
+ ```ruby
435
+ Client.where("orders_count = #{params[:orders]}")
436
+ ```
437
+
438
+ 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.
439
+
440
+ TIP: For more information on the dangers of SQL injection, see the [Ruby on Rails Security Guide](security.html#sql-injection).
441
+
442
+ #### Placeholder Conditions
443
+
444
+ Similar to the `(?)` replacement style of params, you can also specify keys/values hash in your array conditions:
445
+
446
+ ```ruby
447
+ Client.where("created_at >= :start_date AND created_at <= :end_date",
448
+ {start_date: params[:start_date], end_date: params[:end_date]})
449
+ ```
450
+
451
+ This makes for clearer readability if you have a large number of variable conditions.
452
+
453
+ ### Hash Conditions
454
+
455
+ 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:
456
+
457
+ NOTE: Only equality, range and subset checking are possible with Hash conditions.
458
+
459
+ #### Equality Conditions
460
+
461
+ ```ruby
462
+ Client.where(locked: true)
463
+ ```
464
+
465
+ The field name can also be a string:
466
+
467
+ ```ruby
468
+ Client.where('locked' => true)
469
+ ```
470
+
471
+ In the case of a belongs_to relationship, an association key can be used to specify the model if an Active Record object is used as the value. This method works with polymorphic relationships as well.
472
+
473
+ ```ruby
474
+ Post.where(author: author)
475
+ Author.joins(:posts).where(posts: {author: author})
476
+ ```
477
+
478
+ NOTE: The values cannot be symbols. For example, you cannot do `Client.where(status: :active)`.
479
+
480
+ #### Range Conditions
481
+
482
+ ```ruby
483
+ Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
484
+ ```
485
+
486
+ This will find all clients created yesterday by using a `BETWEEN` SQL statement:
487
+
488
+ ```sql
489
+ SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
490
+ ```
491
+
492
+ This demonstrates a shorter syntax for the examples in [Array Conditions](#array-conditions)
493
+
494
+ #### Subset Conditions
495
+
496
+ If you want to find records using the `IN` expression you can pass an array to the conditions hash:
497
+
498
+ ```ruby
499
+ Client.where(orders_count: [1,3,5])
500
+ ```
501
+
502
+ This code will generate SQL like this:
503
+
504
+ ```sql
505
+ SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
506
+ ```
507
+
508
+ ### NOT, LIKE, and NOT LIKE Conditions
509
+
510
+ `NOT`, `LIKE`, and `NOT LIKE` SQL queries can be built by `where.not`, `where.like`, and `where.not_like` respectively.
511
+
512
+ ```ruby
513
+ Post.where.not(author: author)
514
+
515
+ Author.where.like(name: 'Nari%')
516
+
517
+ Developer.where.not_like(name: 'Tenderl%')
518
+ ```
519
+
520
+ In other words, these sort of queries can be generated by calling `where` with no argument, then immediately chain with `not`, `like`, or `not_like` passing `where` conditions.
521
+
522
+ Ordering
523
+ --------
524
+
525
+ To retrieve records from the database in a specific order, you can use the `order` method.
526
+
527
+ 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:
528
+
529
+ ```ruby
530
+ Client.order("created_at")
531
+ ```
532
+
533
+ You could specify `ASC` or `DESC` as well:
534
+
535
+ ```ruby
536
+ Client.order("created_at DESC")
537
+ # OR
538
+ Client.order("created_at ASC")
539
+ ```
540
+
541
+ Or ordering by multiple fields:
542
+
543
+ ```ruby
544
+ Client.order("orders_count ASC, created_at DESC")
545
+ # OR
546
+ Client.order("orders_count ASC", "created_at DESC")
547
+ ```
548
+
549
+ If you want to call `order` multiple times e.g. in different context, new order will prepend previous one
550
+
551
+ ```ruby
552
+ Client.order("orders_count ASC").order("created_at DESC")
553
+ # SELECT * FROM clients ORDER BY created_at DESC, orders_count ASC
554
+ ```
555
+
556
+ Selecting Specific Fields
557
+ -------------------------
558
+
559
+ By default, `Model.find` selects all the fields from the result set using `select *`.
560
+
561
+ To select only a subset of fields from the result set, you can specify the subset via the `select` method.
562
+
563
+ For example, to select only `viewable_by` and `locked` columns:
564
+
565
+ ```ruby
566
+ Client.select("viewable_by, locked")
567
+ ```
568
+
569
+ The SQL query used by this find call will be somewhat like:
570
+
571
+ ```sql
572
+ SELECT viewable_by, locked FROM clients
573
+ ```
574
+
575
+ 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:
576
+
577
+ ```bash
578
+ ActiveModel::MissingAttributeError: missing attribute: <attribute>
579
+ ```
580
+
581
+ Where `<attribute>` 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.
582
+
583
+ If you would like to only grab a single record per unique value in a certain field, you can use `uniq`:
584
+
585
+ ```ruby
586
+ Client.select(:name).uniq
587
+ ```
588
+
589
+ This would generate SQL like:
590
+
591
+ ```sql
592
+ SELECT DISTINCT name FROM clients
593
+ ```
594
+
595
+ You can also remove the uniqueness constraint:
596
+
597
+ ```ruby
598
+ query = Client.select(:name).uniq
599
+ # => Returns unique names
600
+
601
+ query.uniq(false)
602
+ # => Returns all names, even if there are duplicates
603
+ ```
604
+
605
+ Limit and Offset
606
+ ----------------
607
+
608
+ To apply `LIMIT` to the SQL fired by the `Model.find`, you can specify the `LIMIT` using `limit` and `offset` methods on the relation.
609
+
610
+ 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
611
+
612
+ ```ruby
613
+ Client.limit(5)
614
+ ```
615
+
616
+ 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:
617
+
618
+ ```sql
619
+ SELECT * FROM clients LIMIT 5
620
+ ```
621
+
622
+ Adding `offset` to that
623
+
624
+ ```ruby
625
+ Client.limit(5).offset(30)
626
+ ```
627
+
628
+ will return instead a maximum of 5 clients beginning with the 31st. The SQL looks like:
629
+
630
+ ```sql
631
+ SELECT * FROM clients LIMIT 5 OFFSET 30
632
+ ```
633
+
634
+ Group
635
+ -----
636
+
637
+ To apply a `GROUP BY` clause to the SQL fired by the finder, you can specify the `group` method on the find.
638
+
639
+ For example, if you want to find a collection of the dates orders were created on:
640
+
641
+ ```ruby
642
+ Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
643
+ ```
644
+
645
+ And this will give you a single `Order` object for each date where there are orders in the database.
646
+
647
+ The SQL that would be executed would be something like this:
648
+
649
+ ```sql
650
+ SELECT date(created_at) as ordered_date, sum(price) as total_price
651
+ FROM orders
652
+ GROUP BY date(created_at)
653
+ ```
654
+
655
+ Having
656
+ ------
657
+
658
+ 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.
659
+
660
+ For example:
661
+
662
+ ```ruby
663
+ Order.select("date(created_at) as ordered_date, sum(price) as total_price").
664
+ group("date(created_at)").having("sum(price) > ?", 100)
665
+ ```
666
+
667
+ The SQL that would be executed would be something like this:
668
+
669
+ ```sql
670
+ SELECT date(created_at) as ordered_date, sum(price) as total_price
671
+ FROM orders
672
+ GROUP BY date(created_at)
673
+ HAVING sum(price) > 100
674
+ ```
675
+
676
+ This will return single order objects for each day, but only those that are ordered more than $100 in a day.
677
+
678
+ Overriding Conditions
679
+ ---------------------
680
+
681
+ ### `except`
682
+
683
+ You can specify certain conditions to be excepted by using the `except` method. For example:
684
+
685
+ ```ruby
686
+ Post.where('id > 10').limit(20).order('id asc').except(:order)
687
+ ```
688
+
689
+ The SQL that would be executed:
690
+
691
+ ```sql
692
+ SELECT * FROM posts WHERE id > 10 LIMIT 20
693
+ ```
694
+
695
+ ### `only`
696
+
697
+ You can also override conditions using the `only` method. For example:
698
+
699
+ ```ruby
700
+ Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
701
+ ```
702
+
703
+ The SQL that would be executed:
704
+
705
+ ```sql
706
+ SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
707
+ ```
708
+
709
+ ### `reorder`
710
+
711
+ The `reorder` method overrides the default scope order. For example:
712
+
713
+ ```ruby
714
+ class Post < ActiveRecord::Base
715
+ ..
716
+ ..
717
+ has_many :comments, order: 'posted_at DESC'
718
+ end
719
+
720
+ Post.find(10).comments.reorder('name')
721
+ ```
722
+
723
+ The SQL that would be executed:
724
+
725
+ ```sql
726
+ SELECT * FROM posts WHERE id = 10 ORDER BY name
727
+ ```
728
+
729
+ In case the `reorder` clause is not used, the SQL executed would be:
730
+
731
+ ```sql
732
+ SELECT * FROM posts WHERE id = 10 ORDER BY posted_at DESC
733
+ ```
734
+
735
+ ### `reverse_order`
736
+
737
+ The `reverse_order` method reverses the ordering clause if specified.
738
+
739
+ ```ruby
740
+ Client.where("orders_count > 10").order(:name).reverse_order
741
+ ```
742
+
743
+ The SQL that would be executed:
744
+
745
+ ```sql
746
+ SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC
747
+ ```
748
+
749
+ If no ordering clause is specified in the query, the `reverse_order` orders by the primary key in reverse order.
750
+
751
+ ```ruby
752
+ Client.where("orders_count > 10").reverse_order
753
+ ```
754
+
755
+ The SQL that would be executed:
756
+
757
+ ```sql
758
+ SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC
759
+ ```
760
+
761
+ This method accepts **no** arguments.
762
+
763
+ Null Relation
764
+ -------------
765
+
766
+ The `none` method returns a chainable relation with no records. Any subsequent conditions chained to the returned relation will continue generating empty relations. This is useful in scenarios where you need a chainable response to a method or a scope that could return zero results.
767
+
768
+ ```ruby
769
+ Post.none # returns an empty Relation and fires no queries.
770
+ ```
771
+
772
+ ```ruby
773
+ # The visible_posts method below is expected to return a Relation.
774
+ @posts = current_user.visible_posts.where(name: params[:name])
775
+
776
+ def visible_posts
777
+ case role
778
+ when 'Country Manager'
779
+ Post.where(country: country)
780
+ when 'Reviewer'
781
+ Post.published
782
+ when 'Bad User'
783
+ Post.none # => returning [] or nil breaks the caller code in this case
784
+ end
785
+ end
786
+ ```
787
+
788
+ Readonly Objects
789
+ ----------------
790
+
791
+ Active Record provides `readonly` method on a relation to explicitly disallow modification of any of the returned objects. Any attempt to alter a readonly record will not succeed, raising an `ActiveRecord::ReadOnlyRecord` exception.
792
+
793
+ ```ruby
794
+ client = Client.readonly.first
795
+ client.visits += 1
796
+ client.save
797
+ ```
798
+
799
+ 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_.
800
+
801
+ Locking Records for Update
802
+ --------------------------
803
+
804
+ Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.
805
+
806
+ Active Record provides two locking mechanisms:
807
+
808
+ * Optimistic Locking
809
+ * Pessimistic Locking
810
+
811
+ ### Optimistic Locking
812
+
813
+ 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.
814
+
815
+ **Optimistic locking column**
816
+
817
+ In order to use optimistic locking, the table needs to have a column called `lock_version` of type integer. 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:
818
+
819
+ ```ruby
820
+ c1 = Client.find(1)
821
+ c2 = Client.find(1)
822
+
823
+ c1.first_name = "Michael"
824
+ c1.save
825
+
826
+ c2.name = "should fail"
827
+ c2.save # Raises an ActiveRecord::StaleObjectError
828
+ ```
829
+
830
+ 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.
831
+
832
+ This behavior can be turned off by setting `ActiveRecord::Base.lock_optimistically = false`.
833
+
834
+ To override the name of the `lock_version` column, `ActiveRecord::Base` provides a class attribute called `locking_column`:
835
+
836
+ ```ruby
837
+ class Client < ActiveRecord::Base
838
+ self.locking_column = :lock_client_column
839
+ end
840
+ ```
841
+
842
+ ### Pessimistic Locking
843
+
844
+ 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.
845
+
846
+ For example:
847
+
848
+ ```ruby
849
+ Item.transaction do
850
+ i = Item.lock.first
851
+ i.name = 'Jones'
852
+ i.save
853
+ end
854
+ ```
855
+
856
+ The above session produces the following SQL for a MySQL backend:
857
+
858
+ ```sql
859
+ SQL (0.2ms) BEGIN
860
+ Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
861
+ Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
862
+ SQL (0.8ms) COMMIT
863
+ ```
864
+
865
+ 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:
866
+
867
+ ```ruby
868
+ Item.transaction do
869
+ i = Item.lock("LOCK IN SHARE MODE").find(1)
870
+ i.increment!(:views)
871
+ end
872
+ ```
873
+
874
+ 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:
875
+
876
+ ```ruby
877
+ item = Item.first
878
+ item.with_lock do
879
+ # This block is called within a transaction,
880
+ # item is already locked.
881
+ item.increment!(:views)
882
+ end
883
+ ```
884
+
885
+ Joining Tables
886
+ --------------
887
+
888
+ 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.
889
+
890
+ ### Using a String SQL Fragment
891
+
892
+ You can just supply the raw SQL specifying the `JOIN` clause to `joins`:
893
+
894
+ ```ruby
895
+ Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
896
+ ```
897
+
898
+ This will result in the following SQL:
899
+
900
+ ```sql
901
+ SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
902
+ ```
903
+
904
+ ### Using Array/Hash of Named Associations
905
+
906
+ WARNING: This method only works with `INNER JOIN`.
907
+
908
+ 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.
909
+
910
+ For example, consider the following `Category`, `Post`, `Comments` and `Guest` models:
911
+
912
+ ```ruby
913
+ class Category < ActiveRecord::Base
914
+ has_many :posts
915
+ end
916
+
917
+ class Post < ActiveRecord::Base
918
+ belongs_to :category
919
+ has_many :comments
920
+ has_many :tags
921
+ end
922
+
923
+ class Comment < ActiveRecord::Base
924
+ belongs_to :post
925
+ has_one :guest
926
+ end
927
+
928
+ class Guest < ActiveRecord::Base
929
+ belongs_to :comment
930
+ end
931
+
932
+ class Tag < ActiveRecord::Base
933
+ belongs_to :post
934
+ end
935
+ ```
936
+
937
+ Now all of the following will produce the expected join queries using `INNER JOIN`:
938
+
939
+ #### Joining a Single Association
940
+
941
+ ```ruby
942
+ Category.joins(:posts)
943
+ ```
944
+
945
+ This produces:
946
+
947
+ ```sql
948
+ SELECT categories.* FROM categories
949
+ INNER JOIN posts ON posts.category_id = categories.id
950
+ ```
951
+
952
+ 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(:posts).select("distinct(categories.id)")`.
953
+
954
+ #### Joining Multiple Associations
955
+
956
+ ```ruby
957
+ Post.joins(:category, :comments)
958
+ ```
959
+
960
+ This produces:
961
+
962
+ ```sql
963
+ SELECT posts.* FROM posts
964
+ INNER JOIN categories ON posts.category_id = categories.id
965
+ INNER JOIN comments ON comments.post_id = posts.id
966
+ ```
967
+
968
+ 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.
969
+
970
+ #### Joining Nested Associations (Single Level)
971
+
972
+ ```ruby
973
+ Post.joins(comments: :guest)
974
+ ```
975
+
976
+ This produces:
977
+
978
+ ```sql
979
+ SELECT posts.* FROM posts
980
+ INNER JOIN comments ON comments.post_id = posts.id
981
+ INNER JOIN guests ON guests.comment_id = comments.id
982
+ ```
983
+
984
+ Or, in English: "return all posts that have a comment made by a guest."
985
+
986
+ #### Joining Nested Associations (Multiple Level)
987
+
988
+ ```ruby
989
+ Category.joins(posts: [{comments: :guest}, :tags])
990
+ ```
991
+
992
+ This produces:
993
+
994
+ ```sql
995
+ SELECT categories.* FROM categories
996
+ INNER JOIN posts ON posts.category_id = categories.id
997
+ INNER JOIN comments ON comments.post_id = posts.id
998
+ INNER JOIN guests ON guests.comment_id = comments.id
999
+ INNER JOIN tags ON tags.post_id = posts.id
1000
+ ```
1001
+
1002
+ ### Specifying Conditions on the Joined Tables
1003
+
1004
+ 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:
1005
+
1006
+ ```ruby
1007
+ time_range = (Time.now.midnight - 1.day)..Time.now.midnight
1008
+ Client.joins(:orders).where('orders.created_at' => time_range)
1009
+ ```
1010
+
1011
+ An alternative and cleaner syntax is to nest the hash conditions:
1012
+
1013
+ ```ruby
1014
+ time_range = (Time.now.midnight - 1.day)..Time.now.midnight
1015
+ Client.joins(:orders).where(orders: {created_at: time_range})
1016
+ ```
1017
+
1018
+ This will find all clients who have orders that were created yesterday, again using a `BETWEEN` SQL expression.
1019
+
1020
+ Eager Loading Associations
1021
+ --------------------------
1022
+
1023
+ Eager loading is the mechanism for loading the associated records of the objects returned by `Model.find` using as few queries as possible.
1024
+
1025
+ **N + 1 queries problem**
1026
+
1027
+ Consider the following code, which finds 10 clients and prints their postcodes:
1028
+
1029
+ ```ruby
1030
+ clients = Client.limit(10)
1031
+
1032
+ clients.each do |client|
1033
+ puts client.address.postcode
1034
+ end
1035
+ ```
1036
+
1037
+ 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) + 10 (one per each client to load the address) = **11** queries in total.
1038
+
1039
+ **Solution to N + 1 queries problem**
1040
+
1041
+ 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.
1042
+
1043
+ Revisiting the above case, we could rewrite `Client.limit(10)` to use eager load addresses:
1044
+
1045
+ ```ruby
1046
+ clients = Client.includes(:address).limit(10)
1047
+
1048
+ clients.each do |client|
1049
+ puts client.address.postcode
1050
+ end
1051
+ ```
1052
+
1053
+ The above code will execute just **2** queries, as opposed to **11** queries in the previous case:
1054
+
1055
+ ```sql
1056
+ SELECT * FROM clients LIMIT 10
1057
+ SELECT addresses.* FROM addresses
1058
+ WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
1059
+ ```
1060
+
1061
+ ### Eager Loading Multiple Associations
1062
+
1063
+ 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.
1064
+
1065
+ #### Array of Multiple Associations
1066
+
1067
+ ```ruby
1068
+ Post.includes(:category, :comments)
1069
+ ```
1070
+
1071
+ This loads all the posts and the associated category and comments for each post.
1072
+
1073
+ #### Nested Associations Hash
1074
+
1075
+ ```ruby
1076
+ Category.includes(posts: [{comments: :guest}, :tags]).find(1)
1077
+ ```
1078
+
1079
+ 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.
1080
+
1081
+ ### Specifying Conditions on Eager Loaded Associations
1082
+
1083
+ 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.
1084
+
1085
+ However if you must do this, you may use `where` as you would normally.
1086
+
1087
+ ```ruby
1088
+ Post.includes(:comments).where("comments.visible" => true)
1089
+ ```
1090
+
1091
+ This would generate a query which contains a `LEFT OUTER JOIN` whereas the `joins` method would generate one using the `INNER JOIN` function instead.
1092
+
1093
+ ```ruby
1094
+ 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)
1095
+ ```
1096
+
1097
+ If there was no `where` condition, this would generate the normal set of two queries.
1098
+
1099
+ 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.
1100
+
1101
+ Scopes
1102
+ ------
1103
+
1104
+ Scoping allows you to specify commonly-used 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.
1105
+
1106
+ To define a simple scope, we use the `scope` method inside the class, passing the query that we'd like to run when this scope is called:
1107
+
1108
+ ```ruby
1109
+ class Post < ActiveRecord::Base
1110
+ scope :published, -> { where(published: true) }
1111
+ end
1112
+ ```
1113
+
1114
+ This is exactly the same as defining a class method, and which you use is a matter of personal preference:
1115
+
1116
+ ```ruby
1117
+ class Post < ActiveRecord::Base
1118
+ def self.published
1119
+ where(published: true)
1120
+ end
1121
+ end
1122
+ ```
1123
+
1124
+ Scopes are also chainable within scopes:
1125
+
1126
+ ```ruby
1127
+ class Post < ActiveRecord::Base
1128
+ scope :published, -> { where(published: true) }
1129
+ scope :published_and_commented, -> { published.where("comments_count > 0") }
1130
+ end
1131
+ ```
1132
+
1133
+ To call this `published` scope we can call it on either the class:
1134
+
1135
+ ```ruby
1136
+ Post.published # => [published posts]
1137
+ ```
1138
+
1139
+ Or on an association consisting of `Post` objects:
1140
+
1141
+ ```ruby
1142
+ category = Category.first
1143
+ category.posts.published # => [published posts belonging to this category]
1144
+ ```
1145
+
1146
+ ### Passing in arguments
1147
+
1148
+ Your scope can take arguments:
1149
+
1150
+ ```ruby
1151
+ class Post < ActiveRecord::Base
1152
+ scope :created_before, ->(time) { where("created_at < ?", time) }
1153
+ end
1154
+ ```
1155
+
1156
+ This may then be called using this:
1157
+
1158
+ ```ruby
1159
+ Post.created_before(Time.zone.now)
1160
+ ```
1161
+
1162
+ However, this is just duplicating the functionality that would be provided to you by a class method.
1163
+
1164
+ ```ruby
1165
+ class Post < ActiveRecord::Base
1166
+ def self.created_before(time)
1167
+ where("created_at < ?", time)
1168
+ end
1169
+ end
1170
+ ```
1171
+
1172
+ Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:
1173
+
1174
+ ```ruby
1175
+ category.posts.created_before(time)
1176
+ ```
1177
+
1178
+ ### Applying a default scope
1179
+
1180
+ If we wish for a scope to be applied across all queries to the model we can use the
1181
+ `default_scope` method within the model itself.
1182
+
1183
+ ```ruby
1184
+ class Client < ActiveRecord::Base
1185
+ default_scope { where("removed_at IS NULL") }
1186
+ end
1187
+ ```
1188
+
1189
+ When queries are executed on this model, the SQL query will now look something like
1190
+ this:
1191
+
1192
+ ```sql
1193
+ SELECT * FROM clients WHERE removed_at IS NULL
1194
+ ```
1195
+
1196
+ If you need to do more complex things with a default scope, you can alternatively
1197
+ define it as a class method:
1198
+
1199
+ ```ruby
1200
+ class Client < ActiveRecord::Base
1201
+ def self.default_scope
1202
+ # Should return an ActiveRecord::Relation.
1203
+ end
1204
+ end
1205
+ ```
1206
+
1207
+ ### Removing All Scoping
1208
+
1209
+ If we wish to remove scoping for any reason we can use the `unscoped` method. This is
1210
+ especially useful if a `default_scope` is specified in the model and should not be
1211
+ applied for this particular query.
1212
+
1213
+ ```ruby
1214
+ Client.unscoped.all
1215
+ ```
1216
+
1217
+ This method removes all scoping and will do a normal query on the table.
1218
+
1219
+ Note that chaining `unscoped` with a `scope` does not work. In these cases, it is
1220
+ recommended that you use the block form of `unscoped`:
1221
+
1222
+ ```ruby
1223
+ Client.unscoped {
1224
+ Client.created_before(Time.zome.now)
1225
+ }
1226
+ ```
1227
+
1228
+ Dynamic Finders
1229
+ ---------------
1230
+
1231
+ 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` for free from Active Record. If you have a `locked` field on the `Client` model, you also get `find_by_locked` and methods.
1232
+
1233
+ You can specify an exclamation point (`!`) 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")`
1234
+
1235
+ 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)`.
1236
+
1237
+ Find or Build a New Object
1238
+ --------------------------
1239
+
1240
+ It's common that you need to find a record or create it if it doesn't exist. You can do that with the `find_or_create_by` and `find_or_create_by!` methods.
1241
+
1242
+ ### `find_or_create_by`
1243
+
1244
+ The `find_or_create_by` method checks whether a record with the attributes exists. If it doesn't, then `create` is called. Let's see an example.
1245
+
1246
+ Suppose you want to find a client named 'Andy', and if there's none, create one. You can do so by running:
1247
+
1248
+ ```ruby
1249
+ Client.find_or_create_by(first_name: 'Andy')
1250
+ # => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
1251
+ ```
1252
+
1253
+ The SQL generated by this method looks like this:
1254
+
1255
+ ```sql
1256
+ SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
1257
+ BEGIN
1258
+ INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 1, NULL, '2011-08-30 05:22:57')
1259
+ COMMIT
1260
+ ```
1261
+
1262
+ `find_or_create_by` 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.
1263
+
1264
+ The new record might not be saved to the database; that depends on whether validations passed or not (just like `create`).
1265
+
1266
+ Suppose we want to set the 'locked' attribute to true if we're
1267
+ creating a new record, but we don't want to include it in the query. So
1268
+ we want to find the client named "Andy", or if that client doesn't
1269
+ exist, create a client named "Andy" which is not locked.
1270
+
1271
+ We can achieve this in two ways. The first is to use `create_with`:
1272
+
1273
+ ```ruby
1274
+ Client.create_with(locked: false).find_or_create_by(first_name: 'Andy')
1275
+ ```
1276
+
1277
+ The second way is using a block:
1278
+
1279
+ ```ruby
1280
+ Client.find_or_create_by(first_name: 'Andy') do |c|
1281
+ c.locked = false
1282
+ end
1283
+ ```
1284
+
1285
+ The block will only be executed if the client is being created. The
1286
+ second time we run this code, the block will be ignored.
1287
+
1288
+ ### `find_or_create_by!`
1289
+
1290
+ You can also use `find_or_create_by!` 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
1291
+
1292
+ ```ruby
1293
+ validates :orders_count, presence: true
1294
+ ```
1295
+
1296
+ 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:
1297
+
1298
+ ```ruby
1299
+ Client.find_or_create_by!(first_name: 'Andy')
1300
+ # => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
1301
+ ```
1302
+
1303
+ ### `find_or_initialize_by`
1304
+
1305
+ The `find_or_initialize_by` method will work just like
1306
+ `find_or_create_by` but it will call `new` instead of `create`. This
1307
+ means that a new model instance will be created in memory but won't be
1308
+ saved to the database. Continuing with the `find_or_create_by` example, we
1309
+ now want the client named 'Nick':
1310
+
1311
+ ```ruby
1312
+ nick = Client.find_or_initialize_by(first_name: 'Nick')
1313
+ # => <Client id: nil, first_name: "Nick", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
1314
+
1315
+ nick.persisted?
1316
+ # => false
1317
+
1318
+ nick.new_record?
1319
+ # => true
1320
+ ```
1321
+
1322
+ Because the object is not yet stored in the database, the SQL generated looks like this:
1323
+
1324
+ ```sql
1325
+ SELECT * FROM clients WHERE (clients.first_name = 'Nick') LIMIT 1
1326
+ ```
1327
+
1328
+ When you want to save it to the database, just call `save`:
1329
+
1330
+ ```ruby
1331
+ nick.save
1332
+ # => true
1333
+ ```
1334
+
1335
+ Finding by SQL
1336
+ --------------
1337
+
1338
+ 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:
1339
+
1340
+ ```ruby
1341
+ Client.find_by_sql("SELECT * FROM clients
1342
+ INNER JOIN orders ON clients.id = orders.client_id
1343
+ ORDER clients.created_at desc")
1344
+ ```
1345
+
1346
+ `find_by_sql` provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
1347
+
1348
+ ### `select_all`
1349
+
1350
+ `find_by_sql` 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.
1351
+
1352
+ ```ruby
1353
+ Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
1354
+ ```
1355
+
1356
+ ### `pluck`
1357
+
1358
+ `pluck` can be used to query a single or multiple columns from the underlying table of a model. It accepts a list of column names as argument and returns an array of values of the specified columns with the corresponding data type.
1359
+
1360
+ ```ruby
1361
+ Client.where(active: true).pluck(:id)
1362
+ # SELECT id FROM clients WHERE active = 1
1363
+ # => [1, 2, 3]
1364
+
1365
+ Client.uniq.pluck(:role)
1366
+ # SELECT DISTINCT role FROM clients
1367
+ # => ['admin', 'member', 'guest']
1368
+
1369
+ Client.pluck(:id, :name)
1370
+ # SELECT clients.id, clients.name FROM clients
1371
+ # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
1372
+ ```
1373
+
1374
+ `pluck` makes it possible to replace code like
1375
+
1376
+ ```ruby
1377
+ Client.select(:id).map { |c| c.id }
1378
+ # or
1379
+ Client.select(:id).map(&:id)
1380
+ # or
1381
+ Client.select(:id).map { |c| [c.id, c.name] }
1382
+ ```
1383
+
1384
+ with
1385
+
1386
+ ```ruby
1387
+ Client.pluck(:id)
1388
+ # or
1389
+ Client.pluck(:id, :name)
1390
+ ```
1391
+
1392
+ ### `ids`
1393
+
1394
+ `ids` can be used to pluck all the IDs for the relation using the table's primary key.
1395
+
1396
+ ```ruby
1397
+ Person.ids
1398
+ # SELECT id FROM people
1399
+ ```
1400
+
1401
+ ```ruby
1402
+ class Person < ActiveRecord::Base
1403
+ self.primary_key = "person_id"
1404
+ end
1405
+
1406
+ Person.ids
1407
+ # SELECT person_id FROM people
1408
+ ```
1409
+
1410
+ Existence of Objects
1411
+ --------------------
1412
+
1413
+ 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`.
1414
+
1415
+ ```ruby
1416
+ Client.exists?(1)
1417
+ ```
1418
+
1419
+ The `exists?` method also takes multiple ids, but the catch is that it will return true if any one of those records exists.
1420
+
1421
+ ```ruby
1422
+ Client.exists?(1,2,3)
1423
+ # or
1424
+ Client.exists?([1,2,3])
1425
+ ```
1426
+
1427
+ It's even possible to use `exists?` without any arguments on a model or a relation.
1428
+
1429
+ ```ruby
1430
+ Client.where(first_name: 'Ryan').exists?
1431
+ ```
1432
+
1433
+ The above returns `true` if there is at least one client with the `first_name` 'Ryan' and `false` otherwise.
1434
+
1435
+ ```ruby
1436
+ Client.exists?
1437
+ ```
1438
+
1439
+ The above returns `false` if the `clients` table is empty and `true` otherwise.
1440
+
1441
+ You can also use `any?` and `many?` to check for existence on a model or relation.
1442
+
1443
+ ```ruby
1444
+ # via a model
1445
+ Post.any?
1446
+ Post.many?
1447
+
1448
+ # via a named scope
1449
+ Post.recent.any?
1450
+ Post.recent.many?
1451
+
1452
+ # via a relation
1453
+ Post.where(published: true).any?
1454
+ Post.where(published: true).many?
1455
+
1456
+ # via an association
1457
+ Post.first.categories.any?
1458
+ Post.first.categories.many?
1459
+ ```
1460
+
1461
+ Calculations
1462
+ ------------
1463
+
1464
+ This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
1465
+
1466
+ All calculation methods work directly on a model:
1467
+
1468
+ ```ruby
1469
+ Client.count
1470
+ # SELECT count(*) AS count_all FROM clients
1471
+ ```
1472
+
1473
+ Or on a relation:
1474
+
1475
+ ```ruby
1476
+ Client.where(first_name: 'Ryan').count
1477
+ # SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
1478
+ ```
1479
+
1480
+ You can also use various finder methods on a relation for performing complex calculations:
1481
+
1482
+ ```ruby
1483
+ Client.includes("orders").where(first_name: 'Ryan', orders: {status: 'received'}).count
1484
+ ```
1485
+
1486
+ Which will execute:
1487
+
1488
+ ```sql
1489
+ SELECT count(DISTINCT clients.id) AS count_all FROM clients
1490
+ LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
1491
+ (clients.first_name = 'Ryan' AND orders.status = 'received')
1492
+ ```
1493
+
1494
+ ### Count
1495
+
1496
+ 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)`.
1497
+
1498
+ For options, please see the parent section, [Calculations](#calculations).
1499
+
1500
+ ### Average
1501
+
1502
+ 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:
1503
+
1504
+ ```ruby
1505
+ Client.average("orders_count")
1506
+ ```
1507
+
1508
+ This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
1509
+
1510
+ For options, please see the parent section, [Calculations](#calculations).
1511
+
1512
+ ### Minimum
1513
+
1514
+ 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:
1515
+
1516
+ ```ruby
1517
+ Client.minimum("age")
1518
+ ```
1519
+
1520
+ For options, please see the parent section, [Calculations](#calculations).
1521
+
1522
+ ### Maximum
1523
+
1524
+ 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:
1525
+
1526
+ ```ruby
1527
+ Client.maximum("age")
1528
+ ```
1529
+
1530
+ For options, please see the parent section, [Calculations](#calculations).
1531
+
1532
+ ### Sum
1533
+
1534
+ 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:
1535
+
1536
+ ```ruby
1537
+ Client.sum("orders_count")
1538
+ ```
1539
+
1540
+ For options, please see the parent section, [Calculations](#calculations).
1541
+
1542
+ Running EXPLAIN
1543
+ ---------------
1544
+
1545
+ You can run EXPLAIN on the queries triggered by relations. For example,
1546
+
1547
+ ```ruby
1548
+ User.where(id: 1).joins(:posts).explain
1549
+ ```
1550
+
1551
+ may yield
1552
+
1553
+ ```
1554
+ EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `posts` ON `posts`.`user_id` = `users`.`id` WHERE `users`.`id` = 1
1555
+ +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
1556
+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
1557
+ +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
1558
+ | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
1559
+ | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
1560
+ +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
1561
+ 2 rows in set (0.00 sec)
1562
+ ```
1563
+
1564
+ under MySQL.
1565
+
1566
+ Active Record performs a pretty printing that emulates the one of the database
1567
+ shells. So, the same query running with the PostgreSQL adapter would yield instead
1568
+
1569
+ ```
1570
+ EXPLAIN for: SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" WHERE "users"."id" = 1
1571
+ QUERY PLAN
1572
+ ------------------------------------------------------------------------------
1573
+ Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
1574
+ Join Filter: (posts.user_id = users.id)
1575
+ -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
1576
+ Index Cond: (id = 1)
1577
+ -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4)
1578
+ Filter: (posts.user_id = 1)
1579
+ (6 rows)
1580
+ ```
1581
+
1582
+ Eager loading may trigger more than one query under the hood, and some queries
1583
+ may need the results of previous ones. Because of that, `explain` actually
1584
+ executes the query, and then asks for the query plans. For example,
1585
+
1586
+ ```ruby
1587
+ User.where(id: 1).includes(:posts).explain
1588
+ ```
1589
+
1590
+ yields
1591
+
1592
+ ```
1593
+ EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
1594
+ +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1595
+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
1596
+ +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1597
+ | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
1598
+ +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1599
+ 1 row in set (0.00 sec)
1600
+
1601
+ EXPLAIN for: SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1)
1602
+ +----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1603
+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
1604
+ +----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1605
+ | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
1606
+ +----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1607
+ 1 row in set (0.00 sec)
1608
+ ```
1609
+
1610
+ under MySQL.
1611
+
1612
+ ### Interpreting EXPLAIN
1613
+
1614
+ Interpretation of the output of EXPLAIN is beyond the scope of this guide. The
1615
+ following pointers may be helpful:
1616
+
1617
+ * SQLite3: [EXPLAIN QUERY PLAN](http://www.sqlite.org/eqp.html)
1618
+
1619
+ * MySQL: [EXPLAIN Output Format](http://dev.mysql.com/doc/refman/5.6/en/explain-output.html)
1620
+
1621
+ * PostgreSQL: [Using EXPLAIN](http://www.postgresql.org/docs/current/static/using-explain.html)