rails 4.1.0 → 5.2.0

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