rails 4.2.0.beta4 → 4.2.0.rc1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (230) hide show
  1. checksums.yaml +4 -4
  2. data/guides/Rakefile +3 -1
  3. data/guides/bug_report_templates/action_controller_gem.rb +2 -2
  4. data/guides/bug_report_templates/action_controller_master.rb +2 -2
  5. data/guides/source/3_0_release_notes.md +2 -2
  6. data/guides/source/4_1_release_notes.md +1 -1
  7. data/guides/source/4_2_release_notes.md +250 -225
  8. data/guides/source/_welcome.html.erb +1 -1
  9. data/guides/source/action_controller_overview.md +6 -6
  10. data/guides/source/action_mailer_basics.md +26 -11
  11. data/guides/source/action_view_overview.md +0 -1
  12. data/guides/source/active_job_basics.md +29 -23
  13. data/guides/source/active_record_postgresql.md +2 -7
  14. data/guides/source/active_record_validations.md +1 -0
  15. data/guides/source/active_support_core_extensions.md +1 -1
  16. data/guides/source/active_support_instrumentation.md +5 -5
  17. data/guides/source/asset_pipeline.md +2 -2
  18. data/guides/source/association_basics.md +0 -2
  19. data/guides/source/command_line.md +6 -15
  20. data/guides/source/configuring.md +4 -4
  21. data/guides/source/documents.yaml +0 -1
  22. data/guides/source/engines.md +26 -15
  23. data/guides/source/form_helpers.md +10 -2
  24. data/guides/source/getting_started.md +9 -9
  25. data/guides/source/rails_on_rack.md +2 -2
  26. data/guides/source/ruby_on_rails_guides_guidelines.md +1 -0
  27. data/guides/source/security.md +1 -1
  28. data/guides/source/testing.md +80 -13
  29. data/guides/source/upgrading_ruby_on_rails.md +23 -20
  30. metadata +29 -229
  31. data/guides/output/2_2_release_notes.html +0 -724
  32. data/guides/output/2_3_release_notes.html +0 -870
  33. data/guides/output/3_0_release_notes.html +0 -773
  34. data/guides/output/3_1_release_notes.html +0 -740
  35. data/guides/output/3_2_release_notes.html +0 -797
  36. data/guides/output/4_0_release_notes.html +0 -523
  37. data/guides/output/4_1_release_notes.html +0 -806
  38. data/guides/output/4_2_release_notes.html +0 -728
  39. data/guides/output/Gemfile +0 -6
  40. data/guides/output/_license.html +0 -226
  41. data/guides/output/_welcome.html +0 -233
  42. data/guides/output/action_controller_overview.html +0 -1335
  43. data/guides/output/action_mailer_basics.html +0 -928
  44. data/guides/output/action_view_overview.html +0 -1509
  45. data/guides/output/active_job_basics.html +0 -546
  46. data/guides/output/active_model_basics.html +0 -438
  47. data/guides/output/active_record_basics.html +0 -594
  48. data/guides/output/active_record_callbacks.html +0 -592
  49. data/guides/output/active_record_migrations.html +0 -1123
  50. data/guides/output/active_record_postgresql.html +0 -675
  51. data/guides/output/active_record_querying.html +0 -1796
  52. data/guides/output/active_record_validations.html +0 -1301
  53. data/guides/output/active_support_core_extensions.html +0 -3450
  54. data/guides/output/active_support_instrumentation.html +0 -1121
  55. data/guides/output/api_documentation_guidelines.html +0 -498
  56. data/guides/output/asset_pipeline.html +0 -1167
  57. data/guides/output/association_basics.html +0 -2086
  58. data/guides/output/caching_with_rails.html +0 -553
  59. data/guides/output/command_line.html +0 -791
  60. data/guides/output/configuring.html +0 -1055
  61. data/guides/output/contributing_to_ruby_on_rails.html +0 -657
  62. data/guides/output/credits.html +0 -284
  63. data/guides/output/debugging_rails_applications.html +0 -1014
  64. data/guides/output/development_dependencies_install.html +0 -478
  65. data/guides/output/engines.html +0 -1438
  66. data/guides/output/form_helpers.html +0 -1074
  67. data/guides/output/generators.html +0 -838
  68. data/guides/output/getting_started.html +0 -2092
  69. data/guides/output/i18n.html +0 -1198
  70. data/guides/output/images/akshaysurve.jpg +0 -0
  71. data/guides/output/images/belongs_to.png +0 -0
  72. data/guides/output/images/book_icon.gif +0 -0
  73. data/guides/output/images/bullet.gif +0 -0
  74. data/guides/output/images/chapters_icon.gif +0 -0
  75. data/guides/output/images/check_bullet.gif +0 -0
  76. data/guides/output/images/credits_pic_blank.gif +0 -0
  77. data/guides/output/images/csrf.png +0 -0
  78. data/guides/output/images/edge_badge.png +0 -0
  79. data/guides/output/images/favicon.ico +0 -0
  80. data/guides/output/images/feature_tile.gif +0 -0
  81. data/guides/output/images/footer_tile.gif +0 -0
  82. data/guides/output/images/fxn.png +0 -0
  83. data/guides/output/images/getting_started/article_with_comments.png +0 -0
  84. data/guides/output/images/getting_started/challenge.png +0 -0
  85. data/guides/output/images/getting_started/confirm_dialog.png +0 -0
  86. data/guides/output/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  87. data/guides/output/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  88. data/guides/output/images/getting_started/form_with_errors.png +0 -0
  89. data/guides/output/images/getting_started/index_action_with_edit_link.png +0 -0
  90. data/guides/output/images/getting_started/new_article.png +0 -0
  91. data/guides/output/images/getting_started/new_post.png +0 -0
  92. data/guides/output/images/getting_started/post_with_comments.png +0 -0
  93. data/guides/output/images/getting_started/rails_welcome.png +0 -0
  94. data/guides/output/images/getting_started/routing_error_no_controller.png +0 -0
  95. data/guides/output/images/getting_started/routing_error_no_route_matches.png +0 -0
  96. data/guides/output/images/getting_started/show_action_for_articles.png +0 -0
  97. data/guides/output/images/getting_started/show_action_for_posts.png +0 -0
  98. data/guides/output/images/getting_started/template_is_missing_articles_new.png +0 -0
  99. data/guides/output/images/getting_started/template_is_missing_posts_new.png +0 -0
  100. data/guides/output/images/getting_started/undefined_method_post_path.png +0 -0
  101. data/guides/output/images/getting_started/unknown_action_create_for_articles.png +0 -0
  102. data/guides/output/images/getting_started/unknown_action_create_for_posts.png +0 -0
  103. data/guides/output/images/getting_started/unknown_action_new_for_articles.png +0 -0
  104. data/guides/output/images/getting_started/unknown_action_new_for_posts.png +0 -0
  105. data/guides/output/images/grey_bullet.gif +0 -0
  106. data/guides/output/images/habtm.png +0 -0
  107. data/guides/output/images/has_many.png +0 -0
  108. data/guides/output/images/has_many_through.png +0 -0
  109. data/guides/output/images/has_one.png +0 -0
  110. data/guides/output/images/has_one_through.png +0 -0
  111. data/guides/output/images/header_backdrop.png +0 -0
  112. data/guides/output/images/header_tile.gif +0 -0
  113. data/guides/output/images/i18n/demo_html_safe.png +0 -0
  114. data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
  115. data/guides/output/images/i18n/demo_translated_en.png +0 -0
  116. data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
  117. data/guides/output/images/i18n/demo_translation_missing.png +0 -0
  118. data/guides/output/images/i18n/demo_untranslated.png +0 -0
  119. data/guides/output/images/icons/README +0 -5
  120. data/guides/output/images/icons/callouts/1.png +0 -0
  121. data/guides/output/images/icons/callouts/10.png +0 -0
  122. data/guides/output/images/icons/callouts/11.png +0 -0
  123. data/guides/output/images/icons/callouts/12.png +0 -0
  124. data/guides/output/images/icons/callouts/13.png +0 -0
  125. data/guides/output/images/icons/callouts/14.png +0 -0
  126. data/guides/output/images/icons/callouts/15.png +0 -0
  127. data/guides/output/images/icons/callouts/2.png +0 -0
  128. data/guides/output/images/icons/callouts/3.png +0 -0
  129. data/guides/output/images/icons/callouts/4.png +0 -0
  130. data/guides/output/images/icons/callouts/5.png +0 -0
  131. data/guides/output/images/icons/callouts/6.png +0 -0
  132. data/guides/output/images/icons/callouts/7.png +0 -0
  133. data/guides/output/images/icons/callouts/8.png +0 -0
  134. data/guides/output/images/icons/callouts/9.png +0 -0
  135. data/guides/output/images/icons/caution.png +0 -0
  136. data/guides/output/images/icons/example.png +0 -0
  137. data/guides/output/images/icons/home.png +0 -0
  138. data/guides/output/images/icons/important.png +0 -0
  139. data/guides/output/images/icons/next.png +0 -0
  140. data/guides/output/images/icons/note.png +0 -0
  141. data/guides/output/images/icons/prev.png +0 -0
  142. data/guides/output/images/icons/tip.png +0 -0
  143. data/guides/output/images/icons/up.png +0 -0
  144. data/guides/output/images/icons/warning.png +0 -0
  145. data/guides/output/images/nav_arrow.gif +0 -0
  146. data/guides/output/images/oscardelben.jpg +0 -0
  147. data/guides/output/images/polymorphic.png +0 -0
  148. data/guides/output/images/radar.png +0 -0
  149. data/guides/output/images/rails4_features.png +0 -0
  150. data/guides/output/images/rails_guides_kindle_cover.jpg +0 -0
  151. data/guides/output/images/rails_guides_logo.gif +0 -0
  152. data/guides/output/images/rails_logo_remix.gif +0 -0
  153. data/guides/output/images/session_fixation.png +0 -0
  154. data/guides/output/images/tab_grey.gif +0 -0
  155. data/guides/output/images/tab_info.gif +0 -0
  156. data/guides/output/images/tab_note.gif +0 -0
  157. data/guides/output/images/tab_red.gif +0 -0
  158. data/guides/output/images/tab_yellow.gif +0 -0
  159. data/guides/output/images/tab_yellow.png +0 -0
  160. data/guides/output/images/vijaydev.jpg +0 -0
  161. data/guides/output/index.html +0 -354
  162. data/guides/output/initialization.html +0 -876
  163. data/guides/output/javascripts/guides.js +0 -59
  164. data/guides/output/javascripts/jquery.min.js +0 -4
  165. data/guides/output/javascripts/responsive-tables.js +0 -43
  166. data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  167. data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  168. data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  169. data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  170. data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  171. data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  172. data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  173. data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  174. data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  175. data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  176. data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  177. data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  178. data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  179. data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  180. data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  181. data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  182. data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  183. data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  184. data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  185. data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  186. data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  187. data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  188. data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  189. data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  190. data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  191. data/guides/output/javascripts/syntaxhighlighter/shCore.js +0 -17
  192. data/guides/output/layout.html +0 -448
  193. data/guides/output/layouts_and_rendering.html +0 -1541
  194. data/guides/output/maintenance_policy.html +0 -257
  195. data/guides/output/migrations.html +0 -1360
  196. data/guides/output/nested_model_forms.html +0 -412
  197. data/guides/output/plugins.html +0 -644
  198. data/guides/output/rails_application_templates.html +0 -450
  199. data/guides/output/rails_on_rack.html +0 -547
  200. data/guides/output/routing.html +0 -1631
  201. data/guides/output/ruby_on_rails_guides_guidelines.html +0 -329
  202. data/guides/output/security.html +0 -935
  203. data/guides/output/stylesheets/fixes.css +0 -16
  204. data/guides/output/stylesheets/kindle.css +0 -11
  205. data/guides/output/stylesheets/main.css +0 -713
  206. data/guides/output/stylesheets/print.css +0 -52
  207. data/guides/output/stylesheets/reset.css +0 -43
  208. data/guides/output/stylesheets/responsive-tables.css +0 -50
  209. data/guides/output/stylesheets/style.css +0 -13
  210. data/guides/output/stylesheets/syntaxhighlighter/shCore.css +0 -226
  211. data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  212. data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  213. data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  214. data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  215. data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  216. data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  217. data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  218. data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  219. data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  220. data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  221. data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  222. data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  223. data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  224. data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  225. data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  226. data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  227. data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  228. data/guides/output/testing.html +0 -1350
  229. data/guides/output/upgrading_ruby_on_rails.html +0 -1135
  230. data/guides/output/working_with_javascript_in_rails.html +0 -587
@@ -1,1796 +0,0 @@
1
- <!DOCTYPE html>
2
-
3
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4
- <head>
5
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
6
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
7
-
8
- <title>Active Record Query Interface — Ruby on Rails Guides</title>
9
- <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
10
- <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
11
-
12
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
13
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
14
-
15
- <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
16
-
17
- <link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
18
- </head>
19
- <body class="guide">
20
- <div id="topNav">
21
- <div class="wrapper">
22
- <strong class="more-info-label">More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
23
- <span class="red-button more-info-button">
24
- More Ruby on Rails
25
- </span>
26
- <ul class="more-info-links s-hidden">
27
- <li class="more-info"><a href="http://rubyonrails.org/">Overview</a></li>
28
- <li class="more-info"><a href="http://rubyonrails.org/download">Download</a></li>
29
- <li class="more-info"><a href="http://rubyonrails.org/deploy">Deploy</a></li>
30
- <li class="more-info"><a href="https://github.com/rails/rails">Code</a></li>
31
- <li class="more-info"><a href="http://rubyonrails.org/screencasts">Screencasts</a></li>
32
- <li class="more-info"><a href="http://rubyonrails.org/documentation">Documentation</a></li>
33
- <li class="more-info"><a href="http://rubyonrails.org/community">Community</a></li>
34
- <li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
35
- </ul>
36
- </div>
37
- </div>
38
- <div id="header">
39
- <div class="wrapper clearfix">
40
- <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
41
- <ul class="nav">
42
- <li><a class="nav-item" href="index.html">Home</a></li>
43
- <li class="guides-index guides-index-large">
44
- <a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Guides Index</a>
45
- <div id="guides" class="clearfix" style="display: none;">
46
- <hr />
47
- <dl class="L">
48
- <dt>Start Here</dt>
49
- <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
50
- <dt>Models</dt>
51
- <dd><a href="active_record_basics.html">Active Record Basics</a></dd>
52
- <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd>
53
- <dd><a href="active_record_validations.html">Active Record Validations</a></dd>
54
- <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd>
55
- <dd><a href="association_basics.html">Active Record Associations</a></dd>
56
- <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
57
- <dt>Views</dt>
58
- <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
59
- <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
60
- <dt>Controllers</dt>
61
- <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
62
- <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
63
- </dl>
64
- <dl class="R">
65
- <dt>Digging Deeper</dt>
66
- <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
67
- <dd><a href="i18n.html">Rails Internationalization API</a></dd>
68
- <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
69
- <dd><a href="active_job_basics.html">Active Job Basics</a></dd>
70
- <dd><a href="security.html">Securing Rails Applications</a></dd>
71
- <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
72
- <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
73
- <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
74
- <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
75
- <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
76
- <dt>Extending Rails</dt>
77
- <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
78
- <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
79
- <dt>Contributing to Ruby on Rails</dt>
80
- <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
81
- <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
82
- <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
83
- <dt>Maintenance Policy</dt>
84
- <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
85
- <dt>Release Notes</dt>
86
- <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
87
- <dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</a></dd>
88
- <dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</a></dd>
89
- <dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</a></dd>
90
- <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
91
- <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
92
- <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
93
- <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
94
- </dl>
95
- </div>
96
- </li>
97
- <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li>
98
- <li><a class="nav-item" href="credits.html">Credits</a></li>
99
- <li class="guides-index guides-index-small">
100
- <select class="guides-index-item nav-item">
101
- <option value="index.html">Guides Index</option>
102
- <optgroup label="Start Here">
103
- <option value="getting_started.html">Getting Started with Rails</option>
104
- </optgroup>
105
- <optgroup label="Models">
106
- <option value="active_record_basics.html">Active Record Basics</option>
107
- <option value="active_record_migrations.html">Active Record Migrations</option>
108
- <option value="active_record_validations.html">Active Record Validations</option>
109
- <option value="active_record_callbacks.html">Active Record Callbacks</option>
110
- <option value="association_basics.html">Active Record Associations</option>
111
- <option value="active_record_querying.html">Active Record Query Interface</option>
112
- </optgroup>
113
- <optgroup label="Views">
114
- <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
115
- <option value="form_helpers.html">Action View Form Helpers</option>
116
- </optgroup>
117
- <optgroup label="Controllers">
118
- <option value="action_controller_overview.html">Action Controller Overview</option>
119
- <option value="routing.html">Rails Routing from the Outside In</option>
120
- </optgroup>
121
- <optgroup label="Digging Deeper">
122
- <option value="active_support_core_extensions.html">Active Support Core Extensions</option>
123
- <option value="i18n.html">Rails Internationalization API</option>
124
- <option value="action_mailer_basics.html">Action Mailer Basics</option>
125
- <option value="active_job_basics.html">Active Job Basics</option>
126
- <option value="security.html">Securing Rails Applications</option>
127
- <option value="debugging_rails_applications.html">Debugging Rails Applications</option>
128
- <option value="configuring.html">Configuring Rails Applications</option>
129
- <option value="command_line.html">Rails Command Line Tools and Rake Tasks</option>
130
- <option value="asset_pipeline.html">Asset Pipeline</option>
131
- <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
132
- </optgroup>
133
- <optgroup label="Extending Rails">
134
- <option value="rails_on_rack.html">Rails on Rack</option>
135
- <option value="generators.html">Creating and Customizing Rails Generators</option>
136
- </optgroup>
137
- <optgroup label="Contributing to Ruby on Rails">
138
- <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
139
- <option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
140
- <option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</option>
141
- </optgroup>
142
- <optgroup label="Maintenance Policy">
143
- <option value="maintenance_policy.html">Maintenance Policy</option>
144
- </optgroup>
145
- <optgroup label="Release Notes">
146
- <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
147
- <option value="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</option>
148
- <option value="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</option>
149
- <option value="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</option>
150
- <option value="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</option>
151
- <option value="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</option>
152
- <option value="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</option>
153
- <option value="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</option>
154
- </optgroup>
155
- </select>
156
- </li>
157
- </ul>
158
- </div>
159
- </div>
160
- <hr class="hide" />
161
-
162
- <div id="feature">
163
- <div class="wrapper">
164
- <h2>Active Record Query Interface</h2><p>This guide covers different ways to retrieve data from the database using Active Record.</p><p>After reading this guide, you will know:</p>
165
- <ul>
166
- <li>How to find records using a variety of methods and conditions.</li>
167
- <li>How to specify the order, retrieved attributes, grouping, and other properties of the found records.</li>
168
- <li>How to use eager loading to reduce the number of database queries needed for data retrieval.</li>
169
- <li>How to use dynamic finders methods.</li>
170
- <li>How to check for the existence of particular records.</li>
171
- <li>How to perform various calculations on Active Record models.</li>
172
- <li>How to run EXPLAIN on relations.</li>
173
- </ul>
174
-
175
-
176
- <div id="subCol">
177
- <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
178
- <ol class="chapters">
179
- <li>
180
- <a href="#retrieving-objects-from-the-database">Retrieving Objects from the Database</a>
181
-
182
- <ul>
183
- <li><a href="#retrieving-a-single-object">Retrieving a Single Object</a></li>
184
- <li><a href="#retrieving-multiple-objects-in-batches">Retrieving Multiple Objects in Batches</a></li>
185
- </ul>
186
- </li>
187
- <li>
188
- <a href="#conditions">Conditions</a>
189
-
190
- <ul>
191
- <li><a href="#pure-string-conditions">Pure String Conditions</a></li>
192
- <li><a href="#array-conditions">Array Conditions</a></li>
193
- <li><a href="#hash-conditions">Hash Conditions</a></li>
194
- <li><a href="#not-conditions">NOT Conditions</a></li>
195
- </ul>
196
- </li>
197
- <li><a href="#ordering">Ordering</a></li>
198
- <li><a href="#selecting-specific-fields">Selecting Specific Fields</a></li>
199
- <li><a href="#limit-and-offset">Limit and Offset</a></li>
200
- <li>
201
- <a href="#group">Group</a>
202
-
203
- <ul>
204
- <li><a href="#total-of-grouped-items">Total of grouped items</a></li>
205
- </ul>
206
- </li>
207
- <li><a href="#having">Having</a></li>
208
- <li>
209
- <a href="#overriding-conditions">Overriding Conditions</a>
210
-
211
- <ul>
212
- <li><a href="#unscope"><code>unscope</code></a></li>
213
- <li><a href="#only"><code>only</code></a></li>
214
- <li><a href="#reorder"><code>reorder</code></a></li>
215
- <li><a href="#reverse_order"><code>reverse_order</code></a></li>
216
- <li><a href="#rewhere"><code>rewhere</code></a></li>
217
- </ul>
218
- </li>
219
- <li><a href="#null-relation">Null Relation</a></li>
220
- <li><a href="#readonly-objects">Readonly Objects</a></li>
221
- <li>
222
- <a href="#locking-records-for-update">Locking Records for Update</a>
223
-
224
- <ul>
225
- <li><a href="#optimistic-locking">Optimistic Locking</a></li>
226
- <li><a href="#pessimistic-locking">Pessimistic Locking</a></li>
227
- </ul>
228
- </li>
229
- <li>
230
- <a href="#joining-tables">Joining Tables</a>
231
-
232
- <ul>
233
- <li><a href="#using-a-string-sql-fragment">Using a String SQL Fragment</a></li>
234
- <li><a href="#using-array/hash-of-named-associations">Using Array/Hash of Named Associations</a></li>
235
- <li><a href="#specifying-conditions-on-the-joined-tables">Specifying Conditions on the Joined Tables</a></li>
236
- </ul>
237
- </li>
238
- <li>
239
- <a href="#eager-loading-associations">Eager Loading Associations</a>
240
-
241
- <ul>
242
- <li><a href="#eager-loading-multiple-associations">Eager Loading Multiple Associations</a></li>
243
- <li><a href="#specifying-conditions-on-eager-loaded-associations">Specifying Conditions on Eager Loaded Associations</a></li>
244
- </ul>
245
- </li>
246
- <li>
247
- <a href="#scopes">Scopes</a>
248
-
249
- <ul>
250
- <li><a href="#passing-in-arguments">Passing in arguments</a></li>
251
- <li><a href="#applying-a-default-scope">Applying a default scope</a></li>
252
- <li><a href="#merging-of-scopes">Merging of scopes</a></li>
253
- <li><a href="#removing-all-scoping">Removing All Scoping</a></li>
254
- </ul>
255
- </li>
256
- <li><a href="#dynamic-finders">Dynamic Finders</a></li>
257
- <li>
258
- <a href="#find-or-build-a-new-object">Find or Build a New Object</a>
259
-
260
- <ul>
261
- <li><a href="#find_or_create_by"><code>find_or_create_by</code></a></li>
262
- <li><a href="#find_or_create_by-bang"><code>find_or_create_by!</code></a></li>
263
- <li><a href="#find_or_initialize_by"><code>find_or_initialize_by</code></a></li>
264
- </ul>
265
- </li>
266
- <li>
267
- <a href="#finding-by-sql">Finding by SQL</a>
268
-
269
- <ul>
270
- <li><a href="#select_all"><code>select_all</code></a></li>
271
- <li><a href="#pluck"><code>pluck</code></a></li>
272
- <li><a href="#ids"><code>ids</code></a></li>
273
- </ul>
274
- </li>
275
- <li><a href="#existence-of-objects">Existence of Objects</a></li>
276
- <li>
277
- <a href="#calculations">Calculations</a>
278
-
279
- <ul>
280
- <li><a href="#count">Count</a></li>
281
- <li><a href="#average">Average</a></li>
282
- <li><a href="#minimum">Minimum</a></li>
283
- <li><a href="#maximum">Maximum</a></li>
284
- <li><a href="#sum">Sum</a></li>
285
- </ul>
286
- </li>
287
- <li>
288
- <a href="#running-explain">Running EXPLAIN</a>
289
-
290
- <ul>
291
- <li><a href="#interpreting-explain">Interpreting EXPLAIN</a></li>
292
- </ul>
293
- </li>
294
- </ol>
295
-
296
- </div>
297
-
298
- </div>
299
- </div>
300
-
301
- <div id="container">
302
- <div class="wrapper">
303
- <div id="mainCol">
304
- <p>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.</p><p>Code examples throughout this guide will refer to one or more of the following models:</p><div class="info"><p>All of the following models use <code>id</code> as the primary key, unless specified otherwise.</p></div><div class="code_container">
305
- <pre class="brush: ruby; gutter: false; toolbar: false">
306
- class Client &lt; ActiveRecord::Base
307
- has_one :address
308
- has_many :orders
309
- has_and_belongs_to_many :roles
310
- end
311
-
312
- </pre>
313
- </div>
314
- <div class="code_container">
315
- <pre class="brush: ruby; gutter: false; toolbar: false">
316
- class Address &lt; ActiveRecord::Base
317
- belongs_to :client
318
- end
319
-
320
- </pre>
321
- </div>
322
- <div class="code_container">
323
- <pre class="brush: ruby; gutter: false; toolbar: false">
324
- class Order &lt; ActiveRecord::Base
325
- belongs_to :client, counter_cache: true
326
- end
327
-
328
- </pre>
329
- </div>
330
- <div class="code_container">
331
- <pre class="brush: ruby; gutter: false; toolbar: false">
332
- class Role &lt; ActiveRecord::Base
333
- has_and_belongs_to_many :clients
334
- end
335
-
336
- </pre>
337
- </div>
338
- <p>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.</p><h3 id="retrieving-objects-from-the-database">1 Retrieving Objects from the Database</h3><p>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.</p><p>The methods are:</p>
339
- <ul>
340
- <li><code>bind</code></li>
341
- <li><code>create_with</code></li>
342
- <li><code>distinct</code></li>
343
- <li><code>eager_load</code></li>
344
- <li><code>extending</code></li>
345
- <li><code>from</code></li>
346
- <li><code>group</code></li>
347
- <li><code>having</code></li>
348
- <li><code>includes</code></li>
349
- <li><code>joins</code></li>
350
- <li><code>limit</code></li>
351
- <li><code>lock</code></li>
352
- <li><code>none</code></li>
353
- <li><code>offset</code></li>
354
- <li><code>order</code></li>
355
- <li><code>preload</code></li>
356
- <li><code>readonly</code></li>
357
- <li><code>references</code></li>
358
- <li><code>reorder</code></li>
359
- <li><code>reverse_order</code></li>
360
- <li><code>select</code></li>
361
- <li><code>uniq</code></li>
362
- <li><code>where</code></li>
363
- </ul>
364
- <p>All of the above methods return an instance of <code>ActiveRecord::Relation</code>.</p><p>The primary operation of <code>Model.find(options)</code> can be summarized as:</p>
365
- <ul>
366
- <li>Convert the supplied options to an equivalent SQL query.</li>
367
- <li>Fire the SQL query and retrieve the corresponding results from the database.</li>
368
- <li>Instantiate the equivalent Ruby object of the appropriate model for every resulting row.</li>
369
- <li>Run <code>after_find</code> callbacks, if any.</li>
370
- </ul>
371
- <h4 id="retrieving-a-single-object">1.1 Retrieving a Single Object</h4><p>Active Record provides several different ways of retrieving a single object.</p><h5 id="find">1.1.1 <code>find</code>
372
- </h5><p>Using the <code>find</code> method, you can retrieve the object corresponding to the specified <em>primary key</em> that matches any supplied options. For example:</p><div class="code_container">
373
- <pre class="brush: ruby; gutter: false; toolbar: false">
374
- # Find the client with primary key (id) 10.
375
- client = Client.find(10)
376
- # =&gt; #&lt;Client id: 10, first_name: "Ryan"&gt;
377
-
378
- </pre>
379
- </div>
380
- <p>The SQL equivalent of the above is:</p><div class="code_container">
381
- <pre class="brush: sql; gutter: false; toolbar: false">
382
- SELECT * FROM clients WHERE (clients.id = 10) LIMIT 1
383
-
384
- </pre>
385
- </div>
386
- <p>The <code>find</code> method will raise an <code>ActiveRecord::RecordNotFound</code> exception if no matching record is found.</p><p>You can also use this method to query for multiple objects. Call the <code>find</code> method and pass in an array of primary keys. The return will be an array containing all of the matching records for the supplied <em>primary keys</em>. For example:</p><div class="code_container">
387
- <pre class="brush: ruby; gutter: false; toolbar: false">
388
- # Find the clients with primary keys 1 and 10.
389
- client = Client.find([1, 10]) # Or even Client.find(1, 10)
390
- # =&gt; [#&lt;Client id: 1, first_name: "Lifo"&gt;, #&lt;Client id: 10, first_name: "Ryan"&gt;]
391
-
392
- </pre>
393
- </div>
394
- <p>The SQL equivalent of the above is:</p><div class="code_container">
395
- <pre class="brush: sql; gutter: false; toolbar: false">
396
- SELECT * FROM clients WHERE (clients.id IN (1,10))
397
-
398
- </pre>
399
- </div>
400
- <div class="warning"><p>The <code>find</code> method will raise an <code>ActiveRecord::RecordNotFound</code> exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.</p></div><h5 id="take">1.1.2 <code>take</code>
401
- </h5><p>The <code>take</code> method retrieves a record without any implicit ordering. For example:</p><div class="code_container">
402
- <pre class="brush: ruby; gutter: false; toolbar: false">
403
- client = Client.take
404
- # =&gt; #&lt;Client id: 1, first_name: "Lifo"&gt;
405
-
406
- </pre>
407
- </div>
408
- <p>The SQL equivalent of the above is:</p><div class="code_container">
409
- <pre class="brush: sql; gutter: false; toolbar: false">
410
- SELECT * FROM clients LIMIT 1
411
-
412
- </pre>
413
- </div>
414
- <p>The <code>take</code> method returns <code>nil</code> if no record is found and no exception will be raised.</p><p>You can pass in a numerical argument to the <code>take</code> method to return up to that number of results. For example</p><div class="code_container">
415
- <pre class="brush: ruby; gutter: false; toolbar: false">
416
- client = Client.take(2)
417
- # =&gt; [
418
- #&lt;Client id: 1, first_name: "Lifo"&gt;,
419
- #&lt;Client id: 220, first_name: "Sara"&gt;
420
- ]
421
-
422
- </pre>
423
- </div>
424
- <p>The SQL equivalent of the above is:</p><div class="code_container">
425
- <pre class="brush: sql; gutter: false; toolbar: false">
426
- SELECT * FROM clients LIMIT 2
427
-
428
- </pre>
429
- </div>
430
- <p>The <code>take!</code> method behaves exactly like <code>take</code>, except that it will raise <code>ActiveRecord::RecordNotFound</code> if no matching record is found.</p><div class="info"><p>The retrieved record may vary depending on the database engine.</p></div><h5 id="first">1.1.3 <code>first</code>
431
- </h5><p>The <code>first</code> method finds the first record ordered by the primary key. For example:</p><div class="code_container">
432
- <pre class="brush: ruby; gutter: false; toolbar: false">
433
- client = Client.first
434
- # =&gt; #&lt;Client id: 1, first_name: "Lifo"&gt;
435
-
436
- </pre>
437
- </div>
438
- <p>The SQL equivalent of the above is:</p><div class="code_container">
439
- <pre class="brush: sql; gutter: false; toolbar: false">
440
- SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
441
-
442
- </pre>
443
- </div>
444
- <p>The <code>first</code> method returns <code>nil</code> if no matching record is found and no exception will be raised.</p><p>You can pass in a numerical argument to the <code>first</code> method to return up to that number of results. For example</p><div class="code_container">
445
- <pre class="brush: ruby; gutter: false; toolbar: false">
446
- client = Client.first(3)
447
- # =&gt; [
448
- #&lt;Client id: 1, first_name: "Lifo"&gt;,
449
- #&lt;Client id: 2, first_name: "Fifo"&gt;,
450
- #&lt;Client id: 3, first_name: "Filo"&gt;
451
- ]
452
-
453
- </pre>
454
- </div>
455
- <p>The SQL equivalent of the above is:</p><div class="code_container">
456
- <pre class="brush: sql; gutter: false; toolbar: false">
457
- SELECT * FROM clients ORDER BY clients.id ASC LIMIT 3
458
-
459
- </pre>
460
- </div>
461
- <p>The <code>first!</code> method behaves exactly like <code>first</code>, except that it will raise <code>ActiveRecord::RecordNotFound</code> if no matching record is found.</p><h5 id="last">1.1.4 <code>last</code>
462
- </h5><p>The <code>last</code> method finds the last record ordered by the primary key. For example:</p><div class="code_container">
463
- <pre class="brush: ruby; gutter: false; toolbar: false">
464
- client = Client.last
465
- # =&gt; #&lt;Client id: 221, first_name: "Russel"&gt;
466
-
467
- </pre>
468
- </div>
469
- <p>The SQL equivalent of the above is:</p><div class="code_container">
470
- <pre class="brush: sql; gutter: false; toolbar: false">
471
- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
472
-
473
- </pre>
474
- </div>
475
- <p>The <code>last</code> method returns <code>nil</code> if no matching record is found and no exception will be raised.</p><p>You can pass in a numerical argument to the <code>last</code> method to return up to that number of results. For example</p><div class="code_container">
476
- <pre class="brush: ruby; gutter: false; toolbar: false">
477
- client = Client.last(3)
478
- # =&gt; [
479
- #&lt;Client id: 219, first_name: "James"&gt;,
480
- #&lt;Client id: 220, first_name: "Sara"&gt;,
481
- #&lt;Client id: 221, first_name: "Russel"&gt;
482
- ]
483
-
484
- </pre>
485
- </div>
486
- <p>The SQL equivalent of the above is:</p><div class="code_container">
487
- <pre class="brush: sql; gutter: false; toolbar: false">
488
- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 3
489
-
490
- </pre>
491
- </div>
492
- <p>The <code>last!</code> method behaves exactly like <code>last</code>, except that it will raise <code>ActiveRecord::RecordNotFound</code> if no matching record is found.</p><h5 id="find_by">1.1.5 <code>find_by</code>
493
- </h5><p>The <code>find_by</code> method finds the first record matching some conditions. For example:</p><div class="code_container">
494
- <pre class="brush: ruby; gutter: false; toolbar: false">
495
- Client.find_by first_name: 'Lifo'
496
- # =&gt; #&lt;Client id: 1, first_name: "Lifo"&gt;
497
-
498
- Client.find_by first_name: 'Jon'
499
- # =&gt; nil
500
-
501
- </pre>
502
- </div>
503
- <p>It is equivalent to writing:</p><div class="code_container">
504
- <pre class="brush: ruby; gutter: false; toolbar: false">
505
- Client.where(first_name: 'Lifo').take
506
-
507
- </pre>
508
- </div>
509
- <p>The <code>find_by!</code> method behaves exactly like <code>find_by</code>, except that it will raise <code>ActiveRecord::RecordNotFound</code> if no matching record is found. For example:</p><div class="code_container">
510
- <pre class="brush: ruby; gutter: false; toolbar: false">
511
- Client.find_by! first_name: 'does not exist'
512
- # =&gt; ActiveRecord::RecordNotFound
513
-
514
- </pre>
515
- </div>
516
- <p>This is equivalent to writing:</p><div class="code_container">
517
- <pre class="brush: ruby; gutter: false; toolbar: false">
518
- Client.where(first_name: 'does not exist').take!
519
-
520
- </pre>
521
- </div>
522
- <h4 id="retrieving-multiple-objects-in-batches">1.2 Retrieving Multiple Objects in Batches</h4><p>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.</p><p>This may appear straightforward:</p><div class="code_container">
523
- <pre class="brush: ruby; gutter: false; toolbar: false">
524
- # This is very inefficient when the users table has thousands of rows.
525
- User.all.each do |user|
526
- NewsMailer.weekly(user).deliver
527
- end
528
-
529
- </pre>
530
- </div>
531
- <p>But this approach becomes increasingly impractical as the table size increases, since <code>User.all.each</code> instructs Active Record to fetch <em>the entire table</em> 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.</p><p>Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing. The first method, <code>find_each</code>, retrieves a batch of records and then yields <em>each</em> record to the block individually as a model. The second method, <code>find_in_batches</code>, retrieves a batch of records and then yields <em>the entire batch</em> to the block as an array of models.</p><div class="info"><p>The <code>find_each</code> and <code>find_in_batches</code> 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.</p></div><h5 id="find_each">1.2.1 <code>find_each</code>
532
- </h5><p>The <code>find_each</code> method retrieves a batch of records and then yields <em>each</em> record to the block individually as a model. In the following example, <code>find_each</code> will retrieve 1000 records (the current default for both <code>find_each</code> and <code>find_in_batches</code>) and then yield each record individually to the block as a model. This process is repeated until all of the records have been processed:</p><div class="code_container">
533
- <pre class="brush: ruby; gutter: false; toolbar: false">
534
- User.find_each do |user|
535
- NewsMailer.weekly(user).deliver
536
- end
537
-
538
- </pre>
539
- </div>
540
- <p>To add conditions to a <code>find_each</code> operation you can chain other Active Record methods such as <code>where</code>:</p><div class="code_container">
541
- <pre class="brush: ruby; gutter: false; toolbar: false">
542
- User.where(weekly_subscriber: true).find_each do |user|
543
- NewsMailer.weekly(user).deliver
544
- end
545
-
546
- </pre>
547
- </div>
548
- <h6 id="options-for-find_each">1.2.1.1 Options for <code>find_each</code>
549
- </h6><p>The <code>find_each</code> method accepts most of the options allowed by the regular <code>find</code> method, except for <code>:order</code> and <code>:limit</code>, which are reserved for internal use by <code>find_each</code>.</p><p>Two additional options, <code>:batch_size</code> and <code>:start</code>, are available as well.</p><p><strong><code>:batch_size</code></strong></p><p>The <code>:batch_size</code> 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:</p><div class="code_container">
550
- <pre class="brush: ruby; gutter: false; toolbar: false">
551
- User.find_each(batch_size: 5000) do |user|
552
- NewsMailer.weekly(user).deliver
553
- end
554
-
555
- </pre>
556
- </div>
557
- <p><strong><code>:start</code></strong></p><p>By default, records are fetched in ascending order of the primary key, which must be an integer. The <code>:start</code> 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.</p><p>For example, to send newsletters only to users with the primary key starting from 2000, and to retrieve them in batches of 5000:</p><div class="code_container">
558
- <pre class="brush: ruby; gutter: false; toolbar: false">
559
- User.find_each(start: 2000, batch_size: 5000) do |user|
560
- NewsMailer.weekly(user).deliver
561
- end
562
-
563
- </pre>
564
- </div>
565
- <p>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 <code>:start</code> option on each worker.</p><h5 id="find_in_batches">1.2.2 <code>find_in_batches</code>
566
- </h5><p>The <code>find_in_batches</code> method is similar to <code>find_each</code>, since both retrieve batches of records. The difference is that <code>find_in_batches</code> yields <em>batches</em> 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:</p><div class="code_container">
567
- <pre class="brush: ruby; gutter: false; toolbar: false">
568
- # Give add_invoices an array of 1000 invoices at a time
569
- Invoice.find_in_batches(include: :invoice_lines) do |invoices|
570
- export.add_invoices(invoices)
571
- end
572
-
573
- </pre>
574
- </div>
575
- <div class="note"><p>The <code>:include</code> option allows you to name associations that should be loaded alongside with the models.</p></div><h6 id="options-for-find_in_batches">1.2.2.1 Options for <code>find_in_batches</code>
576
- </h6><p>The <code>find_in_batches</code> method accepts the same <code>:batch_size</code> and <code>:start</code> options as <code>find_each</code>, as well as most of the options allowed by the regular <code>find</code> method, except for <code>:order</code> and <code>:limit</code>, which are reserved for internal use by <code>find_in_batches</code>.</p><h3 id="conditions">2 Conditions</h3><p>The <code>where</code> method allows you to specify conditions to limit the records returned, representing the <code>WHERE</code>-part of the SQL statement. Conditions can either be specified as a string, array, or hash.</p><h4 id="pure-string-conditions">2.1 Pure String Conditions</h4><p>If you'd like to add conditions to your find, you could just specify them in there, just like <code>Client.where("orders_count = '2'")</code>. This will find all clients where the <code>orders_count</code> field's value is 2.</p><div class="warning"><p>Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, <code>Client.where("first_name LIKE '%#{params[:first_name]}%'")</code> is not safe. See the next section for the preferred way to handle conditions using an array.</p></div><h4 id="array-conditions">2.2 Array Conditions</h4><p>Now what if that number could vary, say as an argument from somewhere? The find would then take the form:</p><div class="code_container">
577
- <pre class="brush: ruby; gutter: false; toolbar: false">
578
- Client.where("orders_count = ?", params[:orders])
579
-
580
- </pre>
581
- </div>
582
- <p>Active Record will go through the first element in the conditions value and any additional elements will replace the question marks <code>(?)</code> in the first element.</p><p>If you want to specify multiple conditions:</p><div class="code_container">
583
- <pre class="brush: ruby; gutter: false; toolbar: false">
584
- Client.where("orders_count = ? AND locked = ?", params[:orders], false)
585
-
586
- </pre>
587
- </div>
588
- <p>In this example, the first question mark will be replaced with the value in <code>params[:orders]</code> and the second will be replaced with the SQL representation of <code>false</code>, which depends on the adapter.</p><p>This code is highly preferable:</p><div class="code_container">
589
- <pre class="brush: ruby; gutter: false; toolbar: false">
590
- Client.where("orders_count = ?", params[:orders])
591
-
592
- </pre>
593
- </div>
594
- <p>to this code:</p><div class="code_container">
595
- <pre class="brush: ruby; gutter: false; toolbar: false">
596
- Client.where("orders_count = #{params[:orders]}")
597
-
598
- </pre>
599
- </div>
600
- <p>because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database <strong>as-is</strong>. 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.</p><div class="info"><p>For more information on the dangers of SQL injection, see the <a href="security.html#sql-injection">Ruby on Rails Security Guide</a>.</p></div><h5 id="placeholder-conditions">2.2.1 Placeholder Conditions</h5><p>Similar to the <code>(?)</code> replacement style of params, you can also specify keys/values hash in your array conditions:</p><div class="code_container">
601
- <pre class="brush: ruby; gutter: false; toolbar: false">
602
- Client.where("created_at &gt;= :start_date AND created_at &lt;= :end_date",
603
- {start_date: params[:start_date], end_date: params[:end_date]})
604
-
605
- </pre>
606
- </div>
607
- <p>This makes for clearer readability if you have a large number of variable conditions.</p><h4 id="hash-conditions">2.3 Hash Conditions</h4><p>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:</p><div class="note"><p>Only equality, range and subset checking are possible with Hash conditions.</p></div><h5 id="equality-conditions">2.3.1 Equality Conditions</h5><div class="code_container">
608
- <pre class="brush: ruby; gutter: false; toolbar: false">
609
- Client.where(locked: true)
610
-
611
- </pre>
612
- </div>
613
- <p>The field name can also be a string:</p><div class="code_container">
614
- <pre class="brush: ruby; gutter: false; toolbar: false">
615
- Client.where('locked' =&gt; true)
616
-
617
- </pre>
618
- </div>
619
- <p>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.</p><div class="code_container">
620
- <pre class="brush: ruby; gutter: false; toolbar: false">
621
- Article.where(author: author)
622
- Author.joins(:articles).where(articles: { author: author })
623
-
624
- </pre>
625
- </div>
626
- <div class="note"><p>The values cannot be symbols. For example, you cannot do <code>Client.where(status: :active)</code>.</p></div><h5 id="range-conditions">2.3.2 Range Conditions</h5><div class="code_container">
627
- <pre class="brush: ruby; gutter: false; toolbar: false">
628
- Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
629
-
630
- </pre>
631
- </div>
632
- <p>This will find all clients created yesterday by using a <code>BETWEEN</code> SQL statement:</p><div class="code_container">
633
- <pre class="brush: sql; gutter: false; toolbar: false">
634
- SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
635
-
636
- </pre>
637
- </div>
638
- <p>This demonstrates a shorter syntax for the examples in <a href="#array-conditions">Array Conditions</a></p><h5 id="subset-conditions">2.3.3 Subset Conditions</h5><p>If you want to find records using the <code>IN</code> expression you can pass an array to the conditions hash:</p><div class="code_container">
639
- <pre class="brush: ruby; gutter: false; toolbar: false">
640
- Client.where(orders_count: [1,3,5])
641
-
642
- </pre>
643
- </div>
644
- <p>This code will generate SQL like this:</p><div class="code_container">
645
- <pre class="brush: sql; gutter: false; toolbar: false">
646
- SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
647
-
648
- </pre>
649
- </div>
650
- <h4 id="not-conditions">2.4 NOT Conditions</h4><p><code>NOT</code> SQL queries can be built by <code>where.not</code>.</p><div class="code_container">
651
- <pre class="brush: ruby; gutter: false; toolbar: false">
652
- Article.where.not(author: author)
653
-
654
- </pre>
655
- </div>
656
- <p>In other words, this query can be generated by calling <code>where</code> with no argument, then immediately chain with <code>not</code> passing <code>where</code> conditions.</p><h3 id="ordering">3 Ordering</h3><p>To retrieve records from the database in a specific order, you can use the <code>order</code> method.</p><p>For example, if you're getting a set of records and want to order them in ascending order by the <code>created_at</code> field in your table:</p><div class="code_container">
657
- <pre class="brush: ruby; gutter: false; toolbar: false">
658
- Client.order(:created_at)
659
- # OR
660
- Client.order("created_at")
661
-
662
- </pre>
663
- </div>
664
- <p>You could specify <code>ASC</code> or <code>DESC</code> as well:</p><div class="code_container">
665
- <pre class="brush: ruby; gutter: false; toolbar: false">
666
- Client.order(created_at: :desc)
667
- # OR
668
- Client.order(created_at: :asc)
669
- # OR
670
- Client.order("created_at DESC")
671
- # OR
672
- Client.order("created_at ASC")
673
-
674
- </pre>
675
- </div>
676
- <p>Or ordering by multiple fields:</p><div class="code_container">
677
- <pre class="brush: ruby; gutter: false; toolbar: false">
678
- Client.order(orders_count: :asc, created_at: :desc)
679
- # OR
680
- Client.order(:orders_count, created_at: :desc)
681
- # OR
682
- Client.order("orders_count ASC, created_at DESC")
683
- # OR
684
- Client.order("orders_count ASC", "created_at DESC")
685
-
686
- </pre>
687
- </div>
688
- <p>If you want to call <code>order</code> multiple times e.g. in different context, new order will append previous one</p><div class="code_container">
689
- <pre class="brush: ruby; gutter: false; toolbar: false">
690
- Client.order("orders_count ASC").order("created_at DESC")
691
- # SELECT * FROM clients ORDER BY orders_count ASC, created_at DESC
692
-
693
- </pre>
694
- </div>
695
- <h3 id="selecting-specific-fields">4 Selecting Specific Fields</h3><p>By default, <code>Model.find</code> selects all the fields from the result set using <code>select *</code>.</p><p>To select only a subset of fields from the result set, you can specify the subset via the <code>select</code> method.</p><p>For example, to select only <code>viewable_by</code> and <code>locked</code> columns:</p><div class="code_container">
696
- <pre class="brush: ruby; gutter: false; toolbar: false">
697
- Client.select("viewable_by, locked")
698
-
699
- </pre>
700
- </div>
701
- <p>The SQL query used by this find call will be somewhat like:</p><div class="code_container">
702
- <pre class="brush: sql; gutter: false; toolbar: false">
703
- SELECT viewable_by, locked FROM clients
704
-
705
- </pre>
706
- </div>
707
- <p>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:</p><div class="code_container">
708
- <pre class="brush: plain; gutter: false; toolbar: false">
709
- ActiveModel::MissingAttributeError: missing attribute: &lt;attribute&gt;
710
-
711
- </pre>
712
- </div>
713
- <p>Where <code>&lt;attribute&gt;</code> is the attribute you asked for. The <code>id</code> method will not raise the <code>ActiveRecord::MissingAttributeError</code>, so just be careful when working with associations because they need the <code>id</code> method to function properly.</p><p>If you would like to only grab a single record per unique value in a certain field, you can use <code>distinct</code>:</p><div class="code_container">
714
- <pre class="brush: ruby; gutter: false; toolbar: false">
715
- Client.select(:name).distinct
716
-
717
- </pre>
718
- </div>
719
- <p>This would generate SQL like:</p><div class="code_container">
720
- <pre class="brush: sql; gutter: false; toolbar: false">
721
- SELECT DISTINCT name FROM clients
722
-
723
- </pre>
724
- </div>
725
- <p>You can also remove the uniqueness constraint:</p><div class="code_container">
726
- <pre class="brush: ruby; gutter: false; toolbar: false">
727
- query = Client.select(:name).distinct
728
- # =&gt; Returns unique names
729
-
730
- query.distinct(false)
731
- # =&gt; Returns all names, even if there are duplicates
732
-
733
- </pre>
734
- </div>
735
- <h3 id="limit-and-offset">5 Limit and Offset</h3><p>To apply <code>LIMIT</code> to the SQL fired by the <code>Model.find</code>, you can specify the <code>LIMIT</code> using <code>limit</code> and <code>offset</code> methods on the relation.</p><p>You can use <code>limit</code> to specify the number of records to be retrieved, and use <code>offset</code> to specify the number of records to skip before starting to return the records. For example</p><div class="code_container">
736
- <pre class="brush: ruby; gutter: false; toolbar: false">
737
- Client.limit(5)
738
-
739
- </pre>
740
- </div>
741
- <p>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:</p><div class="code_container">
742
- <pre class="brush: sql; gutter: false; toolbar: false">
743
- SELECT * FROM clients LIMIT 5
744
-
745
- </pre>
746
- </div>
747
- <p>Adding <code>offset</code> to that</p><div class="code_container">
748
- <pre class="brush: ruby; gutter: false; toolbar: false">
749
- Client.limit(5).offset(30)
750
-
751
- </pre>
752
- </div>
753
- <p>will return instead a maximum of 5 clients beginning with the 31st. The SQL looks like:</p><div class="code_container">
754
- <pre class="brush: sql; gutter: false; toolbar: false">
755
- SELECT * FROM clients LIMIT 5 OFFSET 30
756
-
757
- </pre>
758
- </div>
759
- <h3 id="group">6 Group</h3><p>To apply a <code>GROUP BY</code> clause to the SQL fired by the finder, you can specify the <code>group</code> method on the find.</p><p>For example, if you want to find a collection of the dates orders were created on:</p><div class="code_container">
760
- <pre class="brush: ruby; gutter: false; toolbar: false">
761
- Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
762
-
763
- </pre>
764
- </div>
765
- <p>And this will give you a single <code>Order</code> object for each date where there are orders in the database.</p><p>The SQL that would be executed would be something like this:</p><div class="code_container">
766
- <pre class="brush: sql; gutter: false; toolbar: false">
767
- SELECT date(created_at) as ordered_date, sum(price) as total_price
768
- FROM orders
769
- GROUP BY date(created_at)
770
-
771
- </pre>
772
- </div>
773
- <h4 id="total-of-grouped-items">6.1 Total of grouped items</h4><p>To get the total of grouped items on a single query call <code>count</code> after the <code>group</code>.</p><div class="code_container">
774
- <pre class="brush: ruby; gutter: false; toolbar: false">
775
- Order.group(:status).count
776
- # =&gt; { 'awaiting_approval' =&gt; 7, 'paid' =&gt; 12 }
777
-
778
- </pre>
779
- </div>
780
- <p>The SQL that would be executed would be something like this:</p><div class="code_container">
781
- <pre class="brush: sql; gutter: false; toolbar: false">
782
- SELECT COUNT (*) AS count_all, status AS status
783
- FROM "orders"
784
- GROUP BY status
785
-
786
- </pre>
787
- </div>
788
- <h3 id="having">7 Having</h3><p>SQL uses the <code>HAVING</code> clause to specify conditions on the <code>GROUP BY</code> fields. You can add the <code>HAVING</code> clause to the SQL fired by the <code>Model.find</code> by adding the <code>:having</code> option to the find.</p><p>For example:</p><div class="code_container">
789
- <pre class="brush: ruby; gutter: false; toolbar: false">
790
- Order.select("date(created_at) as ordered_date, sum(price) as total_price").
791
- group("date(created_at)").having("sum(price) &gt; ?", 100)
792
-
793
- </pre>
794
- </div>
795
- <p>The SQL that would be executed would be something like this:</p><div class="code_container">
796
- <pre class="brush: sql; gutter: false; toolbar: false">
797
- SELECT date(created_at) as ordered_date, sum(price) as total_price
798
- FROM orders
799
- GROUP BY date(created_at)
800
- HAVING sum(price) &gt; 100
801
-
802
- </pre>
803
- </div>
804
- <p>This will return single order objects for each day, but only those that are ordered more than $100 in a day.</p><h3 id="overriding-conditions">8 Overriding Conditions</h3><h4 id="unscope">8.1 <code>unscope</code>
805
- </h4><p>You can specify certain conditions to be removed using the <code>unscope</code> method. For example:</p><div class="code_container">
806
- <pre class="brush: ruby; gutter: false; toolbar: false">
807
- Article.where('id &gt; 10').limit(20).order('id asc').unscope(:order)
808
-
809
- </pre>
810
- </div>
811
- <p>The SQL that would be executed:</p><div class="code_container">
812
- <pre class="brush: sql; gutter: false; toolbar: false">
813
- SELECT * FROM articles WHERE id &gt; 10 LIMIT 20
814
-
815
- # Original query without `unscope`
816
- SELECT * FROM articles WHERE id &gt; 10 ORDER BY id asc LIMIT 20
817
-
818
-
819
- </pre>
820
- </div>
821
- <p>You can also unscope specific <code>where</code> clauses. For example:</p><div class="code_container">
822
- <pre class="brush: ruby; gutter: false; toolbar: false">
823
- Article.where(id: 10, trashed: false).unscope(where: :id)
824
- # SELECT "articles".* FROM "articles" WHERE trashed = 0
825
-
826
- </pre>
827
- </div>
828
- <p>A relation which has used <code>unscope</code> will affect any relation it is
829
- merged in to:</p><div class="code_container">
830
- <pre class="brush: ruby; gutter: false; toolbar: false">
831
- Article.order('id asc').merge(Article.unscope(:order))
832
- # SELECT "articles".* FROM "articles"
833
-
834
- </pre>
835
- </div>
836
- <h4 id="only">8.2 <code>only</code>
837
- </h4><p>You can also override conditions using the <code>only</code> method. For example:</p><div class="code_container">
838
- <pre class="brush: ruby; gutter: false; toolbar: false">
839
- Article.where('id &gt; 10').limit(20).order('id desc').only(:order, :where)
840
-
841
- </pre>
842
- </div>
843
- <p>The SQL that would be executed:</p><div class="code_container">
844
- <pre class="brush: sql; gutter: false; toolbar: false">
845
- SELECT * FROM articles WHERE id &gt; 10 ORDER BY id DESC
846
-
847
- # Original query without `only`
848
- SELECT "articles".* FROM "articles" WHERE (id &gt; 10) ORDER BY id desc LIMIT 20
849
-
850
-
851
- </pre>
852
- </div>
853
- <h4 id="reorder">8.3 <code>reorder</code>
854
- </h4><p>The <code>reorder</code> method overrides the default scope order. For example:</p><div class="code_container">
855
- <pre class="brush: ruby; gutter: false; toolbar: false">
856
- class Article &lt; ActiveRecord::Base
857
- has_many :comments, -&gt; { order('posted_at DESC') }
858
- end
859
-
860
- Article.find(10).comments.reorder('name')
861
-
862
- </pre>
863
- </div>
864
- <p>The SQL that would be executed:</p><div class="code_container">
865
- <pre class="brush: sql; gutter: false; toolbar: false">
866
- SELECT * FROM articles WHERE id = 10
867
- SELECT * FROM comments WHERE article_id = 10 ORDER BY name
868
-
869
- </pre>
870
- </div>
871
- <p>In case the <code>reorder</code> clause is not used, the SQL executed would be:</p><div class="code_container">
872
- <pre class="brush: sql; gutter: false; toolbar: false">
873
- SELECT * FROM articles WHERE id = 10
874
- SELECT * FROM comments WHERE article_id = 10 ORDER BY posted_at DESC
875
-
876
- </pre>
877
- </div>
878
- <h4 id="reverse_order">8.4 <code>reverse_order</code>
879
- </h4><p>The <code>reverse_order</code> method reverses the ordering clause if specified.</p><div class="code_container">
880
- <pre class="brush: ruby; gutter: false; toolbar: false">
881
- Client.where("orders_count &gt; 10").order(:name).reverse_order
882
-
883
- </pre>
884
- </div>
885
- <p>The SQL that would be executed:</p><div class="code_container">
886
- <pre class="brush: sql; gutter: false; toolbar: false">
887
- SELECT * FROM clients WHERE orders_count &gt; 10 ORDER BY name DESC
888
-
889
- </pre>
890
- </div>
891
- <p>If no ordering clause is specified in the query, the <code>reverse_order</code> orders by the primary key in reverse order.</p><div class="code_container">
892
- <pre class="brush: ruby; gutter: false; toolbar: false">
893
- Client.where("orders_count &gt; 10").reverse_order
894
-
895
- </pre>
896
- </div>
897
- <p>The SQL that would be executed:</p><div class="code_container">
898
- <pre class="brush: sql; gutter: false; toolbar: false">
899
- SELECT * FROM clients WHERE orders_count &gt; 10 ORDER BY clients.id DESC
900
-
901
- </pre>
902
- </div>
903
- <p>This method accepts <strong>no</strong> arguments.</p><h4 id="rewhere">8.5 <code>rewhere</code>
904
- </h4><p>The <code>rewhere</code> method overrides an existing, named where condition. For example:</p><div class="code_container">
905
- <pre class="brush: ruby; gutter: false; toolbar: false">
906
- Article.where(trashed: true).rewhere(trashed: false)
907
-
908
- </pre>
909
- </div>
910
- <p>The SQL that would be executed:</p><div class="code_container">
911
- <pre class="brush: sql; gutter: false; toolbar: false">
912
- SELECT * FROM articles WHERE `trashed` = 0
913
-
914
- </pre>
915
- </div>
916
- <p>In case the <code>rewhere</code> clause is not used,</p><div class="code_container">
917
- <pre class="brush: ruby; gutter: false; toolbar: false">
918
- Article.where(trashed: true).where(trashed: false)
919
-
920
- </pre>
921
- </div>
922
- <p>the SQL executed would be:</p><div class="code_container">
923
- <pre class="brush: sql; gutter: false; toolbar: false">
924
- SELECT * FROM articles WHERE `trashed` = 1 AND `trashed` = 0
925
-
926
- </pre>
927
- </div>
928
- <h3 id="null-relation">9 Null Relation</h3><p>The <code>none</code> 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.</p><div class="code_container">
929
- <pre class="brush: ruby; gutter: false; toolbar: false">
930
- Article.none # returns an empty Relation and fires no queries.
931
-
932
- </pre>
933
- </div>
934
- <div class="code_container">
935
- <pre class="brush: ruby; gutter: false; toolbar: false">
936
- # The visible_articles method below is expected to return a Relation.
937
- @articles = current_user.visible_articles.where(name: params[:name])
938
-
939
- def visible_articles
940
- case role
941
- when 'Country Manager'
942
- Article.where(country: country)
943
- when 'Reviewer'
944
- Article.published
945
- when 'Bad User'
946
- Article.none # =&gt; returning [] or nil breaks the caller code in this case
947
- end
948
- end
949
-
950
- </pre>
951
- </div>
952
- <h3 id="readonly-objects">10 Readonly Objects</h3><p>Active Record provides <code>readonly</code> 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 <code>ActiveRecord::ReadOnlyRecord</code> exception.</p><div class="code_container">
953
- <pre class="brush: ruby; gutter: false; toolbar: false">
954
- client = Client.readonly.first
955
- client.visits += 1
956
- client.save
957
-
958
- </pre>
959
- </div>
960
- <p>As <code>client</code> is explicitly set to be a readonly object, the above code will raise an <code>ActiveRecord::ReadOnlyRecord</code> exception when calling <code>client.save</code> with an updated value of <em>visits</em>.</p><h3 id="locking-records-for-update">11 Locking Records for Update</h3><p>Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.</p><p>Active Record provides two locking mechanisms:</p>
961
- <ul>
962
- <li>Optimistic Locking</li>
963
- <li>Pessimistic Locking</li>
964
- </ul>
965
- <h4 id="optimistic-locking">11.1 Optimistic Locking</h4><p>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 <code>ActiveRecord::StaleObjectError</code> exception is thrown if that has occurred and the update is ignored.</p><p><strong>Optimistic locking column</strong></p><p>In order to use optimistic locking, the table needs to have a column called <code>lock_version</code> of type integer. Each time the record is updated, Active Record increments the <code>lock_version</code> column. If an update request is made with a lower value in the <code>lock_version</code> field than is currently in the <code>lock_version</code> column in the database, the update request will fail with an <code>ActiveRecord::StaleObjectError</code>. Example:</p><div class="code_container">
966
- <pre class="brush: ruby; gutter: false; toolbar: false">
967
- c1 = Client.find(1)
968
- c2 = Client.find(1)
969
-
970
- c1.first_name = "Michael"
971
- c1.save
972
-
973
- c2.name = "should fail"
974
- c2.save # Raises an ActiveRecord::StaleObjectError
975
-
976
- </pre>
977
- </div>
978
- <p>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.</p><p>This behavior can be turned off by setting <code>ActiveRecord::Base.lock_optimistically = false</code>.</p><p>To override the name of the <code>lock_version</code> column, <code>ActiveRecord::Base</code> provides a class attribute called <code>locking_column</code>:</p><div class="code_container">
979
- <pre class="brush: ruby; gutter: false; toolbar: false">
980
- class Client &lt; ActiveRecord::Base
981
- self.locking_column = :lock_client_column
982
- end
983
-
984
- </pre>
985
- </div>
986
- <h4 id="pessimistic-locking">11.2 Pessimistic Locking</h4><p>Pessimistic locking uses a locking mechanism provided by the underlying database. Using <code>lock</code> when building a relation obtains an exclusive lock on the selected rows. Relations using <code>lock</code> are usually wrapped inside a transaction for preventing deadlock conditions.</p><p>For example:</p><div class="code_container">
987
- <pre class="brush: ruby; gutter: false; toolbar: false">
988
- Item.transaction do
989
- i = Item.lock.first
990
- i.name = 'Jones'
991
- i.save
992
- end
993
-
994
- </pre>
995
- </div>
996
- <p>The above session produces the following SQL for a MySQL backend:</p><div class="code_container">
997
- <pre class="brush: sql; gutter: false; toolbar: false">
998
- SQL (0.2ms) BEGIN
999
- Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
1000
- Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
1001
- SQL (0.8ms) COMMIT
1002
-
1003
- </pre>
1004
- </div>
1005
- <p>You can also pass raw SQL to the <code>lock</code> method for allowing different types of locks. For example, MySQL has an expression called <code>LOCK IN SHARE MODE</code> 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:</p><div class="code_container">
1006
- <pre class="brush: ruby; gutter: false; toolbar: false">
1007
- Item.transaction do
1008
- i = Item.lock("LOCK IN SHARE MODE").find(1)
1009
- i.increment!(:views)
1010
- end
1011
-
1012
- </pre>
1013
- </div>
1014
- <p>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:</p><div class="code_container">
1015
- <pre class="brush: ruby; gutter: false; toolbar: false">
1016
- item = Item.first
1017
- item.with_lock do
1018
- # This block is called within a transaction,
1019
- # item is already locked.
1020
- item.increment!(:views)
1021
- end
1022
-
1023
- </pre>
1024
- </div>
1025
- <h3 id="joining-tables">12 Joining Tables</h3><p>Active Record provides a finder method called <code>joins</code> for specifying <code>JOIN</code> clauses on the resulting SQL. There are multiple ways to use the <code>joins</code> method.</p><h4 id="using-a-string-sql-fragment">12.1 Using a String SQL Fragment</h4><p>You can just supply the raw SQL specifying the <code>JOIN</code> clause to <code>joins</code>:</p><div class="code_container">
1026
- <pre class="brush: ruby; gutter: false; toolbar: false">
1027
- Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
1028
-
1029
- </pre>
1030
- </div>
1031
- <p>This will result in the following SQL:</p><div class="code_container">
1032
- <pre class="brush: sql; gutter: false; toolbar: false">
1033
- SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
1034
-
1035
- </pre>
1036
- </div>
1037
- <h4 id="using-array/hash-of-named-associations">12.2 Using Array/Hash of Named Associations</h4><div class="warning"><p>This method only works with <code>INNER JOIN</code>.</p></div><p>Active Record lets you use the names of the <a href="association_basics.html">associations</a> defined on the model as a shortcut for specifying <code>JOIN</code> clauses for those associations when using the <code>joins</code> method.</p><p>For example, consider the following <code>Category</code>, <code>Article</code>, <code>Comment</code>, <code>Guest</code> and <code>Tag</code> models:</p><div class="code_container">
1038
- <pre class="brush: ruby; gutter: false; toolbar: false">
1039
- class Category &lt; ActiveRecord::Base
1040
- has_many :articles
1041
- end
1042
-
1043
- class Article &lt; ActiveRecord::Base
1044
- belongs_to :category
1045
- has_many :comments
1046
- has_many :tags
1047
- end
1048
-
1049
- class Comment &lt; ActiveRecord::Base
1050
- belongs_to :article
1051
- has_one :guest
1052
- end
1053
-
1054
- class Guest &lt; ActiveRecord::Base
1055
- belongs_to :comment
1056
- end
1057
-
1058
- class Tag &lt; ActiveRecord::Base
1059
- belongs_to :article
1060
- end
1061
-
1062
- </pre>
1063
- </div>
1064
- <p>Now all of the following will produce the expected join queries using <code>INNER JOIN</code>:</p><h5 id="joining-a-single-association">12.2.1 Joining a Single Association</h5><div class="code_container">
1065
- <pre class="brush: ruby; gutter: false; toolbar: false">
1066
- Category.joins(:articles)
1067
-
1068
- </pre>
1069
- </div>
1070
- <p>This produces:</p><div class="code_container">
1071
- <pre class="brush: sql; gutter: false; toolbar: false">
1072
- SELECT categories.* FROM categories
1073
- INNER JOIN articles ON articles.category_id = categories.id
1074
-
1075
- </pre>
1076
- </div>
1077
- <p>Or, in English: "return a Category object for all categories with articles". Note that you will see duplicate categories if more than one article has the same category. If you want unique categories, you can use <code>Category.joins(:articles).uniq</code>.</p><h5 id="joining-multiple-associations">12.2.2 Joining Multiple Associations</h5><div class="code_container">
1078
- <pre class="brush: ruby; gutter: false; toolbar: false">
1079
- Article.joins(:category, :comments)
1080
-
1081
- </pre>
1082
- </div>
1083
- <p>This produces:</p><div class="code_container">
1084
- <pre class="brush: sql; gutter: false; toolbar: false">
1085
- SELECT articles.* FROM articles
1086
- INNER JOIN categories ON articles.category_id = categories.id
1087
- INNER JOIN comments ON comments.article_id = articles.id
1088
-
1089
- </pre>
1090
- </div>
1091
- <p>Or, in English: "return all articles that have a category and at least one comment". Note again that articles with multiple comments will show up multiple times.</p><h5 id="joining-nested-associations-(single-level)">12.2.3 Joining Nested Associations (Single Level)</h5><div class="code_container">
1092
- <pre class="brush: ruby; gutter: false; toolbar: false">
1093
- Article.joins(comments: :guest)
1094
-
1095
- </pre>
1096
- </div>
1097
- <p>This produces:</p><div class="code_container">
1098
- <pre class="brush: sql; gutter: false; toolbar: false">
1099
- SELECT articles.* FROM articles
1100
- INNER JOIN comments ON comments.article_id = articles.id
1101
- INNER JOIN guests ON guests.comment_id = comments.id
1102
-
1103
- </pre>
1104
- </div>
1105
- <p>Or, in English: "return all articles that have a comment made by a guest."</p><h5 id="joining-nested-associations-(multiple-level)">12.2.4 Joining Nested Associations (Multiple Level)</h5><div class="code_container">
1106
- <pre class="brush: ruby; gutter: false; toolbar: false">
1107
- Category.joins(articles: [{ comments: :guest }, :tags])
1108
-
1109
- </pre>
1110
- </div>
1111
- <p>This produces:</p><div class="code_container">
1112
- <pre class="brush: sql; gutter: false; toolbar: false">
1113
- SELECT categories.* FROM categories
1114
- INNER JOIN articles ON articles.category_id = categories.id
1115
- INNER JOIN comments ON comments.article_id = articles.id
1116
- INNER JOIN guests ON guests.comment_id = comments.id
1117
- INNER JOIN tags ON tags.article_id = articles.id
1118
-
1119
- </pre>
1120
- </div>
1121
- <h4 id="specifying-conditions-on-the-joined-tables">12.3 Specifying Conditions on the Joined Tables</h4><p>You can specify conditions on the joined tables using the regular <a href="#array-conditions">Array</a> and <a href="#pure-string-conditions">String</a> conditions. <a href="#hash-conditions">Hash conditions</a> provides a special syntax for specifying conditions for the joined tables:</p><div class="code_container">
1122
- <pre class="brush: ruby; gutter: false; toolbar: false">
1123
- time_range = (Time.now.midnight - 1.day)..Time.now.midnight
1124
- Client.joins(:orders).where('orders.created_at' =&gt; time_range)
1125
-
1126
- </pre>
1127
- </div>
1128
- <p>An alternative and cleaner syntax is to nest the hash conditions:</p><div class="code_container">
1129
- <pre class="brush: ruby; gutter: false; toolbar: false">
1130
- time_range = (Time.now.midnight - 1.day)..Time.now.midnight
1131
- Client.joins(:orders).where(orders: { created_at: time_range })
1132
-
1133
- </pre>
1134
- </div>
1135
- <p>This will find all clients who have orders that were created yesterday, again using a <code>BETWEEN</code> SQL expression.</p><h3 id="eager-loading-associations">13 Eager Loading Associations</h3><p>Eager loading is the mechanism for loading the associated records of the objects returned by <code>Model.find</code> using as few queries as possible.</p><p><strong>N + 1 queries problem</strong></p><p>Consider the following code, which finds 10 clients and prints their postcodes:</p><div class="code_container">
1136
- <pre class="brush: ruby; gutter: false; toolbar: false">
1137
- clients = Client.limit(10)
1138
-
1139
- clients.each do |client|
1140
- puts client.address.postcode
1141
- end
1142
-
1143
- </pre>
1144
- </div>
1145
- <p>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) = <strong>11</strong> queries in total.</p><p><strong>Solution to N + 1 queries problem</strong></p><p>Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the <code>includes</code> method of the <code>Model.find</code> call. With <code>includes</code>, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.</p><p>Revisiting the above case, we could rewrite <code>Client.limit(10)</code> to use eager load addresses:</p><div class="code_container">
1146
- <pre class="brush: ruby; gutter: false; toolbar: false">
1147
- clients = Client.includes(:address).limit(10)
1148
-
1149
- clients.each do |client|
1150
- puts client.address.postcode
1151
- end
1152
-
1153
- </pre>
1154
- </div>
1155
- <p>The above code will execute just <strong>2</strong> queries, as opposed to <strong>11</strong> queries in the previous case:</p><div class="code_container">
1156
- <pre class="brush: sql; gutter: false; toolbar: false">
1157
- SELECT * FROM clients LIMIT 10
1158
- SELECT addresses.* FROM addresses
1159
- WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
1160
-
1161
- </pre>
1162
- </div>
1163
- <h4 id="eager-loading-multiple-associations">13.1 Eager Loading Multiple Associations</h4><p>Active Record lets you eager load any number of associations with a single <code>Model.find</code> call by using an array, hash, or a nested hash of array/hash with the <code>includes</code> method.</p><h5 id="array-of-multiple-associations">13.1.1 Array of Multiple Associations</h5><div class="code_container">
1164
- <pre class="brush: ruby; gutter: false; toolbar: false">
1165
- Article.includes(:category, :comments)
1166
-
1167
- </pre>
1168
- </div>
1169
- <p>This loads all the articles and the associated category and comments for each article.</p><h5 id="nested-associations-hash">13.1.2 Nested Associations Hash</h5><div class="code_container">
1170
- <pre class="brush: ruby; gutter: false; toolbar: false">
1171
- Category.includes(articles: [{ comments: :guest }, :tags]).find(1)
1172
-
1173
- </pre>
1174
- </div>
1175
- <p>This will find the category with id 1 and eager load all of the associated articles, the associated articles' tags and comments, and every comment's guest association.</p><h4 id="specifying-conditions-on-eager-loaded-associations">13.2 Specifying Conditions on Eager Loaded Associations</h4><p>Even though Active Record lets you specify conditions on the eager loaded associations just like <code>joins</code>, the recommended way is to use <a href="#joining-tables">joins</a> instead.</p><p>However if you must do this, you may use <code>where</code> as you would normally.</p><div class="code_container">
1176
- <pre class="brush: ruby; gutter: false; toolbar: false">
1177
- Article.includes(:comments).where(comments: { visible: true })
1178
-
1179
- </pre>
1180
- </div>
1181
- <p>This would generate a query which contains a <code>LEFT OUTER JOIN</code> whereas the
1182
- <code>joins</code> method would generate one using the <code>INNER JOIN</code> function instead.</p><div class="code_container">
1183
- <pre class="brush: ruby; gutter: false; toolbar: false">
1184
- SELECT "articles"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5 FROM "articles" LEFT OUTER JOIN "comments" ON "comments"."article_id" = "articles"."id" WHERE (comments.visible = 1)
1185
-
1186
- </pre>
1187
- </div>
1188
- <p>If there was no <code>where</code> condition, this would generate the normal set of two queries.</p><div class="note"><p>Using <code>where</code> like this will only work when you pass it a Hash. For
1189
- SQL-fragments you need use <code>references</code> to force joined tables:</p></div><div class="code_container">
1190
- <pre class="brush: ruby; gutter: false; toolbar: false">
1191
- Article.includes(:comments).where("comments.visible = true").references(:comments)
1192
-
1193
- </pre>
1194
- </div>
1195
- <p>If, in the case of this <code>includes</code> query, there were no comments for any
1196
- articles, all the articles would still be loaded. By using <code>joins</code> (an INNER
1197
- JOIN), the join conditions <strong>must</strong> match, otherwise no records will be
1198
- returned.</p><h3 id="scopes">14 Scopes</h3><p>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 <code>where</code>, <code>joins</code> and <code>includes</code>. All scope methods will return an <code>ActiveRecord::Relation</code> object which will allow for further methods (such as other scopes) to be called on it.</p><p>To define a simple scope, we use the <code>scope</code> method inside the class, passing the query that we'd like to run when this scope is called:</p><div class="code_container">
1199
- <pre class="brush: ruby; gutter: false; toolbar: false">
1200
- class Article &lt; ActiveRecord::Base
1201
- scope :published, -&gt; { where(published: true) }
1202
- end
1203
-
1204
- </pre>
1205
- </div>
1206
- <p>This is exactly the same as defining a class method, and which you use is a matter of personal preference:</p><div class="code_container">
1207
- <pre class="brush: ruby; gutter: false; toolbar: false">
1208
- class Article &lt; ActiveRecord::Base
1209
- def self.published
1210
- where(published: true)
1211
- end
1212
- end
1213
-
1214
- </pre>
1215
- </div>
1216
- <p>Scopes are also chainable within scopes:</p><div class="code_container">
1217
- <pre class="brush: ruby; gutter: false; toolbar: false">
1218
- class Article &lt; ActiveRecord::Base
1219
- scope :published, -&gt; { where(published: true) }
1220
- scope :published_and_commented, -&gt; { published.where("comments_count &gt; 0") }
1221
- end
1222
-
1223
- </pre>
1224
- </div>
1225
- <p>To call this <code>published</code> scope we can call it on either the class:</p><div class="code_container">
1226
- <pre class="brush: ruby; gutter: false; toolbar: false">
1227
- Article.published # =&gt; [published articles]
1228
-
1229
- </pre>
1230
- </div>
1231
- <p>Or on an association consisting of <code>Article</code> objects:</p><div class="code_container">
1232
- <pre class="brush: ruby; gutter: false; toolbar: false">
1233
- category = Category.first
1234
- category.articles.published # =&gt; [published articles belonging to this category]
1235
-
1236
- </pre>
1237
- </div>
1238
- <h4 id="passing-in-arguments">14.1 Passing in arguments</h4><p>Your scope can take arguments:</p><div class="code_container">
1239
- <pre class="brush: ruby; gutter: false; toolbar: false">
1240
- class Article &lt; ActiveRecord::Base
1241
- scope :created_before, -&gt;(time) { where("created_at &lt; ?", time) }
1242
- end
1243
-
1244
- </pre>
1245
- </div>
1246
- <p>Call the scope as if it were a class method:</p><div class="code_container">
1247
- <pre class="brush: ruby; gutter: false; toolbar: false">
1248
- Article.created_before(Time.zone.now)
1249
-
1250
- </pre>
1251
- </div>
1252
- <p>However, this is just duplicating the functionality that would be provided to you by a class method.</p><div class="code_container">
1253
- <pre class="brush: ruby; gutter: false; toolbar: false">
1254
- class Article &lt; ActiveRecord::Base
1255
- def self.created_before(time)
1256
- where("created_at &lt; ?", time)
1257
- end
1258
- end
1259
-
1260
- </pre>
1261
- </div>
1262
- <p>Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:</p><div class="code_container">
1263
- <pre class="brush: ruby; gutter: false; toolbar: false">
1264
- category.articles.created_before(time)
1265
-
1266
- </pre>
1267
- </div>
1268
- <h4 id="applying-a-default-scope">14.2 Applying a default scope</h4><p>If we wish for a scope to be applied across all queries to the model we can use the
1269
- <code>default_scope</code> method within the model itself.</p><div class="code_container">
1270
- <pre class="brush: ruby; gutter: false; toolbar: false">
1271
- class Client &lt; ActiveRecord::Base
1272
- default_scope { where("removed_at IS NULL") }
1273
- end
1274
-
1275
- </pre>
1276
- </div>
1277
- <p>When queries are executed on this model, the SQL query will now look something like
1278
- this:</p><div class="code_container">
1279
- <pre class="brush: sql; gutter: false; toolbar: false">
1280
- SELECT * FROM clients WHERE removed_at IS NULL
1281
-
1282
- </pre>
1283
- </div>
1284
- <p>If you need to do more complex things with a default scope, you can alternatively
1285
- define it as a class method:</p><div class="code_container">
1286
- <pre class="brush: ruby; gutter: false; toolbar: false">
1287
- class Client &lt; ActiveRecord::Base
1288
- def self.default_scope
1289
- # Should return an ActiveRecord::Relation.
1290
- end
1291
- end
1292
-
1293
- </pre>
1294
- </div>
1295
- <h4 id="merging-of-scopes">14.3 Merging of scopes</h4><p>Just like <code>where</code> clauses scopes are merged using <code>AND</code> conditions.</p><div class="code_container">
1296
- <pre class="brush: ruby; gutter: false; toolbar: false">
1297
- class User &lt; ActiveRecord::Base
1298
- scope :active, -&gt; { where state: 'active' }
1299
- scope :inactive, -&gt; { where state: 'inactive' }
1300
- end
1301
-
1302
- User.active.inactive
1303
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'inactive'
1304
-
1305
- </pre>
1306
- </div>
1307
- <p>We can mix and match <code>scope</code> and <code>where</code> conditions and the final sql
1308
- will have all conditions joined with <code>AND</code>.</p><div class="code_container">
1309
- <pre class="brush: ruby; gutter: false; toolbar: false">
1310
- User.active.where(state: 'finished')
1311
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'finished'
1312
-
1313
- </pre>
1314
- </div>
1315
- <p>If we do want the <code>last where clause</code> to win then <code>Relation#merge</code> can
1316
- be used.</p><div class="code_container">
1317
- <pre class="brush: ruby; gutter: false; toolbar: false">
1318
- User.active.merge(User.inactive)
1319
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
1320
-
1321
- </pre>
1322
- </div>
1323
- <p>One important caveat is that <code>default_scope</code> will be prepended in
1324
- <code>scope</code> and <code>where</code> conditions.</p><div class="code_container">
1325
- <pre class="brush: ruby; gutter: false; toolbar: false">
1326
- class User &lt; ActiveRecord::Base
1327
- default_scope { where state: 'pending' }
1328
- scope :active, -&gt; { where state: 'active' }
1329
- scope :inactive, -&gt; { where state: 'inactive' }
1330
- end
1331
-
1332
- User.all
1333
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
1334
-
1335
- User.active
1336
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'active'
1337
-
1338
- User.where(state: 'inactive')
1339
- # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'inactive'
1340
-
1341
- </pre>
1342
- </div>
1343
- <p>As you can see above the <code>default_scope</code> is being merged in both
1344
- <code>scope</code> and <code>where</code> conditions.</p><h4 id="removing-all-scoping">14.4 Removing All Scoping</h4><p>If we wish to remove scoping for any reason we can use the <code>unscoped</code> method. This is
1345
- especially useful if a <code>default_scope</code> is specified in the model and should not be
1346
- applied for this particular query.</p><div class="code_container">
1347
- <pre class="brush: ruby; gutter: false; toolbar: false">
1348
- Client.unscoped.load
1349
-
1350
- </pre>
1351
- </div>
1352
- <p>This method removes all scoping and will do a normal query on the table.</p><p>Note that chaining <code>unscoped</code> with a <code>scope</code> does not work. In these cases, it is
1353
- recommended that you use the block form of <code>unscoped</code>:</p><div class="code_container">
1354
- <pre class="brush: ruby; gutter: false; toolbar: false">
1355
- Client.unscoped {
1356
- Client.created_before(Time.zone.now)
1357
- }
1358
-
1359
- </pre>
1360
- </div>
1361
- <h3 id="dynamic-finders">15 Dynamic Finders</h3><p>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 <code>first_name</code> on your <code>Client</code> model for example, you get <code>find_by_first_name</code> for free from Active Record. If you have a <code>locked</code> field on the <code>Client</code> model, you also get <code>find_by_locked</code> and methods.</p><p>You can specify an exclamation point (<code>!</code>) on the end of the dynamic finders to get them to raise an <code>ActiveRecord::RecordNotFound</code> error if they do not return any records, like <code>Client.find_by_name!("Ryan")</code></p><p>If you want to find both by name and locked, you can chain these finders together by simply typing "<code>and</code>" between the fields. For example, <code>Client.find_by_first_name_and_locked("Ryan", true)</code>.</p><h3 id="find-or-build-a-new-object">16 Find or Build a New Object</h3><div class="note"><p>Some dynamic finders have been deprecated in Rails 4.0 and will be
1362
- removed in Rails 4.1. The best practice is to use Active Record scopes
1363
- instead. You can find the deprecation gem at
1364
- <a href="https://github.com/rails/activerecord-deprecated_finders">https://github.com/rails/activerecord-deprecated_finders</a></p></div><p>It's common that you need to find a record or create it if it doesn't exist. You can do that with the <code>find_or_create_by</code> and <code>find_or_create_by!</code> methods.</p><h4 id="find_or_create_by">16.1 <code>find_or_create_by</code>
1365
- </h4><p>The <code>find_or_create_by</code> method checks whether a record with the attributes exists. If it doesn't, then <code>create</code> is called. Let's see an example.</p><p>Suppose you want to find a client named 'Andy', and if there's none, create one. You can do so by running:</p><div class="code_container">
1366
- <pre class="brush: ruby; gutter: false; toolbar: false">
1367
- Client.find_or_create_by(first_name: 'Andy')
1368
- # =&gt; #&lt;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"&gt;
1369
-
1370
- </pre>
1371
- </div>
1372
- <p>The SQL generated by this method looks like this:</p><div class="code_container">
1373
- <pre class="brush: sql; gutter: false; toolbar: false">
1374
- SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
1375
- BEGIN
1376
- 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')
1377
- COMMIT
1378
-
1379
- </pre>
1380
- </div>
1381
- <p><code>find_or_create_by</code> 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.</p><p>The new record might not be saved to the database; that depends on whether validations passed or not (just like <code>create</code>).</p><p>Suppose we want to set the 'locked' attribute to <code>false</code> 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.</p><p>We can achieve this in two ways. The first is to use <code>create_with</code>:</p><div class="code_container">
1385
- <pre class="brush: ruby; gutter: false; toolbar: false">
1386
- Client.create_with(locked: false).find_or_create_by(first_name: 'Andy')
1387
-
1388
- </pre>
1389
- </div>
1390
- <p>The second way is using a block:</p><div class="code_container">
1391
- <pre class="brush: ruby; gutter: false; toolbar: false">
1392
- Client.find_or_create_by(first_name: 'Andy') do |c|
1393
- c.locked = false
1394
- end
1395
-
1396
- </pre>
1397
- </div>
1398
- <p>The block will only be executed if the client is being created. The
1399
- second time we run this code, the block will be ignored.</p><h4 id="find_or_create_by-bang">16.2 <code>find_or_create_by!</code>
1400
- </h4><p>You can also use <code>find_or_create_by!</code> 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</p><div class="code_container">
1401
- <pre class="brush: ruby; gutter: false; toolbar: false">
1402
- validates :orders_count, presence: true
1403
-
1404
- </pre>
1405
- </div>
1406
- <p>to your <code>Client</code> model. If you try to create a new <code>Client</code> without passing an <code>orders_count</code>, the record will be invalid and an exception will be raised:</p><div class="code_container">
1407
- <pre class="brush: ruby; gutter: false; toolbar: false">
1408
- Client.find_or_create_by!(first_name: 'Andy')
1409
- # =&gt; ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
1410
-
1411
- </pre>
1412
- </div>
1413
- <h4 id="find_or_initialize_by">16.3 <code>find_or_initialize_by</code>
1414
- </h4><p>The <code>find_or_initialize_by</code> method will work just like
1415
- <code>find_or_create_by</code> but it will call <code>new</code> instead of <code>create</code>. This
1416
- means that a new model instance will be created in memory but won't be
1417
- saved to the database. Continuing with the <code>find_or_create_by</code> example, we
1418
- now want the client named 'Nick':</p><div class="code_container">
1419
- <pre class="brush: ruby; gutter: false; toolbar: false">
1420
- nick = Client.find_or_initialize_by(first_name: 'Nick')
1421
- # =&gt; &lt;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"&gt;
1422
-
1423
- nick.persisted?
1424
- # =&gt; false
1425
-
1426
- nick.new_record?
1427
- # =&gt; true
1428
-
1429
- </pre>
1430
- </div>
1431
- <p>Because the object is not yet stored in the database, the SQL generated looks like this:</p><div class="code_container">
1432
- <pre class="brush: sql; gutter: false; toolbar: false">
1433
- SELECT * FROM clients WHERE (clients.first_name = 'Nick') LIMIT 1
1434
-
1435
- </pre>
1436
- </div>
1437
- <p>When you want to save it to the database, just call <code>save</code>:</p><div class="code_container">
1438
- <pre class="brush: ruby; gutter: false; toolbar: false">
1439
- nick.save
1440
- # =&gt; true
1441
-
1442
- </pre>
1443
- </div>
1444
- <h3 id="finding-by-sql">17 Finding by SQL</h3><p>If you'd like to use your own SQL to find records in a table you can use <code>find_by_sql</code>. The <code>find_by_sql</code> method will return an array of objects even if the underlying query returns just a single record. For example you could run this query:</p><div class="code_container">
1445
- <pre class="brush: ruby; gutter: false; toolbar: false">
1446
- Client.find_by_sql("SELECT * FROM clients
1447
- INNER JOIN orders ON clients.id = orders.client_id
1448
- ORDER BY clients.created_at desc")
1449
- # =&gt; [
1450
- #&lt;Client id: 1, first_name: "Lucas" &gt;,
1451
- #&lt;Client id: 2, first_name: "Jan" &gt;,
1452
- # ...
1453
- ]
1454
-
1455
- </pre>
1456
- </div>
1457
- <p><code>find_by_sql</code> provides you with a simple way of making custom calls to the database and retrieving instantiated objects.</p><h4 id="select_all">17.1 <code>select_all</code>
1458
- </h4><p><code>find_by_sql</code> has a close relative called <code>connection#select_all</code>. <code>select_all</code> will retrieve objects from the database using custom SQL just like <code>find_by_sql</code> but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.</p><div class="code_container">
1459
- <pre class="brush: ruby; gutter: false; toolbar: false">
1460
- Client.connection.select_all("SELECT first_name, created_at FROM clients WHERE id = '1'")
1461
- # =&gt; [
1462
- {"first_name"=&gt;"Rafael", "created_at"=&gt;"2012-11-10 23:23:45.281189"},
1463
- {"first_name"=&gt;"Eileen", "created_at"=&gt;"2013-12-09 11:22:35.221282"}
1464
- ]
1465
-
1466
- </pre>
1467
- </div>
1468
- <h4 id="pluck">17.2 <code>pluck</code>
1469
- </h4><p><code>pluck</code> can be used to query 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.</p><div class="code_container">
1470
- <pre class="brush: ruby; gutter: false; toolbar: false">
1471
- Client.where(active: true).pluck(:id)
1472
- # SELECT id FROM clients WHERE active = 1
1473
- # =&gt; [1, 2, 3]
1474
-
1475
- Client.distinct.pluck(:role)
1476
- # SELECT DISTINCT role FROM clients
1477
- # =&gt; ['admin', 'member', 'guest']
1478
-
1479
- Client.pluck(:id, :name)
1480
- # SELECT clients.id, clients.name FROM clients
1481
- # =&gt; [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
1482
-
1483
- </pre>
1484
- </div>
1485
- <p><code>pluck</code> makes it possible to replace code like:</p><div class="code_container">
1486
- <pre class="brush: ruby; gutter: false; toolbar: false">
1487
- Client.select(:id).map { |c| c.id }
1488
- # or
1489
- Client.select(:id).map(&amp;:id)
1490
- # or
1491
- Client.select(:id, :name).map { |c| [c.id, c.name] }
1492
-
1493
- </pre>
1494
- </div>
1495
- <p>with:</p><div class="code_container">
1496
- <pre class="brush: ruby; gutter: false; toolbar: false">
1497
- Client.pluck(:id)
1498
- # or
1499
- Client.pluck(:id, :name)
1500
-
1501
- </pre>
1502
- </div>
1503
- <p>Unlike <code>select</code>, <code>pluck</code> directly converts a database result into a Ruby <code>Array</code>,
1504
- without constructing <code>ActiveRecord</code> objects. This can mean better performance for
1505
- a large or often-running query. However, any model method overrides will
1506
- not be available. For example:</p><div class="code_container">
1507
- <pre class="brush: ruby; gutter: false; toolbar: false">
1508
- class Client &lt; ActiveRecord::Base
1509
- def name
1510
- "I am #{super}"
1511
- end
1512
- end
1513
-
1514
- Client.select(:name).map &amp;:name
1515
- # =&gt; ["I am David", "I am Jeremy", "I am Jose"]
1516
-
1517
- Client.pluck(:name)
1518
- # =&gt; ["David", "Jeremy", "Jose"]
1519
-
1520
- </pre>
1521
- </div>
1522
- <p>Furthermore, unlike <code>select</code> and other <code>Relation</code> scopes, <code>pluck</code> triggers an immediate
1523
- query, and thus cannot be chained with any further scopes, although it can work with
1524
- scopes already constructed earlier:</p><div class="code_container">
1525
- <pre class="brush: ruby; gutter: false; toolbar: false">
1526
- Client.pluck(:name).limit(1)
1527
- # =&gt; NoMethodError: undefined method `limit' for #&lt;Array:0x007ff34d3ad6d8&gt;
1528
-
1529
- Client.limit(1).pluck(:name)
1530
- # =&gt; ["David"]
1531
-
1532
- </pre>
1533
- </div>
1534
- <h4 id="ids">17.3 <code>ids</code>
1535
- </h4><p><code>ids</code> can be used to pluck all the IDs for the relation using the table's primary key.</p><div class="code_container">
1536
- <pre class="brush: ruby; gutter: false; toolbar: false">
1537
- Person.ids
1538
- # SELECT id FROM people
1539
-
1540
- </pre>
1541
- </div>
1542
- <div class="code_container">
1543
- <pre class="brush: ruby; gutter: false; toolbar: false">
1544
- class Person &lt; ActiveRecord::Base
1545
- self.primary_key = "person_id"
1546
- end
1547
-
1548
- Person.ids
1549
- # SELECT person_id FROM people
1550
-
1551
- </pre>
1552
- </div>
1553
- <h3 id="existence-of-objects">18 Existence of Objects</h3><p>If you simply want to check for the existence of the object there's a method called <code>exists?</code>.
1554
- This method will query the database using the same query as <code>find</code>, but instead of returning an
1555
- object or collection of objects it will return either <code>true</code> or <code>false</code>.</p><div class="code_container">
1556
- <pre class="brush: ruby; gutter: false; toolbar: false">
1557
- Client.exists?(1)
1558
-
1559
- </pre>
1560
- </div>
1561
- <p>The <code>exists?</code> method also takes multiple values, but the catch is that it will return <code>true</code> if any
1562
- one of those records exists.</p><div class="code_container">
1563
- <pre class="brush: ruby; gutter: false; toolbar: false">
1564
- Client.exists?(id: [1,2,3])
1565
- # or
1566
- Client.exists?(name: ['John', 'Sergei'])
1567
-
1568
- </pre>
1569
- </div>
1570
- <p>It's even possible to use <code>exists?</code> without any arguments on a model or a relation.</p><div class="code_container">
1571
- <pre class="brush: ruby; gutter: false; toolbar: false">
1572
- Client.where(first_name: 'Ryan').exists?
1573
-
1574
- </pre>
1575
- </div>
1576
- <p>The above returns <code>true</code> if there is at least one client with the <code>first_name</code> 'Ryan' and <code>false</code>
1577
- otherwise.</p><div class="code_container">
1578
- <pre class="brush: ruby; gutter: false; toolbar: false">
1579
- Client.exists?
1580
-
1581
- </pre>
1582
- </div>
1583
- <p>The above returns <code>false</code> if the <code>clients</code> table is empty and <code>true</code> otherwise.</p><p>You can also use <code>any?</code> and <code>many?</code> to check for existence on a model or relation.</p><div class="code_container">
1584
- <pre class="brush: ruby; gutter: false; toolbar: false">
1585
- # via a model
1586
- Article.any?
1587
- Article.many?
1588
-
1589
- # via a named scope
1590
- Article.recent.any?
1591
- Article.recent.many?
1592
-
1593
- # via a relation
1594
- Article.where(published: true).any?
1595
- Article.where(published: true).many?
1596
-
1597
- # via an association
1598
- Article.first.categories.any?
1599
- Article.first.categories.many?
1600
-
1601
- </pre>
1602
- </div>
1603
- <h3 id="calculations">19 Calculations</h3><p>This section uses count as an example method in this preamble, but the options described apply to all sub-sections.</p><p>All calculation methods work directly on a model:</p><div class="code_container">
1604
- <pre class="brush: ruby; gutter: false; toolbar: false">
1605
- Client.count
1606
- # SELECT count(*) AS count_all FROM clients
1607
-
1608
- </pre>
1609
- </div>
1610
- <p>Or on a relation:</p><div class="code_container">
1611
- <pre class="brush: ruby; gutter: false; toolbar: false">
1612
- Client.where(first_name: 'Ryan').count
1613
- # SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
1614
-
1615
- </pre>
1616
- </div>
1617
- <p>You can also use various finder methods on a relation for performing complex calculations:</p><div class="code_container">
1618
- <pre class="brush: ruby; gutter: false; toolbar: false">
1619
- Client.includes("orders").where(first_name: 'Ryan', orders: { status: 'received' }).count
1620
-
1621
- </pre>
1622
- </div>
1623
- <p>Which will execute:</p><div class="code_container">
1624
- <pre class="brush: sql; gutter: false; toolbar: false">
1625
- SELECT count(DISTINCT clients.id) AS count_all FROM clients
1626
- LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
1627
- (clients.first_name = 'Ryan' AND orders.status = 'received')
1628
-
1629
- </pre>
1630
- </div>
1631
- <h4 id="count">19.1 Count</h4><p>If you want to see how many records are in your model's table you could call <code>Client.count</code> 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 <code>Client.count(:age)</code>.</p><p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p><h4 id="average">19.2 Average</h4><p>If you want to see the average of a certain number in one of your tables you can call the <code>average</code> method on the class that relates to the table. This method call will look something like this:</p><div class="code_container">
1632
- <pre class="brush: ruby; gutter: false; toolbar: false">
1633
- Client.average("orders_count")
1634
-
1635
- </pre>
1636
- </div>
1637
- <p>This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.</p><p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p><h4 id="minimum">19.3 Minimum</h4><p>If you want to find the minimum value of a field in your table you can call the <code>minimum</code> method on the class that relates to the table. This method call will look something like this:</p><div class="code_container">
1638
- <pre class="brush: ruby; gutter: false; toolbar: false">
1639
- Client.minimum("age")
1640
-
1641
- </pre>
1642
- </div>
1643
- <p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p><h4 id="maximum">19.4 Maximum</h4><p>If you want to find the maximum value of a field in your table you can call the <code>maximum</code> method on the class that relates to the table. This method call will look something like this:</p><div class="code_container">
1644
- <pre class="brush: ruby; gutter: false; toolbar: false">
1645
- Client.maximum("age")
1646
-
1647
- </pre>
1648
- </div>
1649
- <p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p><h4 id="sum">19.5 Sum</h4><p>If you want to find the sum of a field for all records in your table you can call the <code>sum</code> method on the class that relates to the table. This method call will look something like this:</p><div class="code_container">
1650
- <pre class="brush: ruby; gutter: false; toolbar: false">
1651
- Client.sum("orders_count")
1652
-
1653
- </pre>
1654
- </div>
1655
- <p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p><h3 id="running-explain">20 Running EXPLAIN</h3><p>You can run EXPLAIN on the queries triggered by relations. For example,</p><div class="code_container">
1656
- <pre class="brush: ruby; gutter: false; toolbar: false">
1657
- User.where(id: 1).joins(:articles).explain
1658
-
1659
- </pre>
1660
- </div>
1661
- <p>may yield</p><div class="code_container">
1662
- <pre class="brush: plain; gutter: false; toolbar: false">
1663
- EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `articles` ON `articles`.`user_id` = `users`.`id` WHERE `users`.`id` = 1
1664
- +----+-------------+----------+-------+---------------+
1665
- | id | select_type | table | type | possible_keys |
1666
- +----+-------------+----------+-------+---------------+
1667
- | 1 | SIMPLE | users | const | PRIMARY |
1668
- | 1 | SIMPLE | articles | ALL | NULL |
1669
- +----+-------------+----------+-------+---------------+
1670
- +---------+---------+-------+------+-------------+
1671
- | key | key_len | ref | rows | Extra |
1672
- +---------+---------+-------+------+-------------+
1673
- | PRIMARY | 4 | const | 1 | |
1674
- | NULL | NULL | NULL | 1 | Using where |
1675
- +---------+---------+-------+------+-------------+
1676
-
1677
- 2 rows in set (0.00 sec)
1678
-
1679
- </pre>
1680
- </div>
1681
- <p>under MySQL.</p><p>Active Record performs a pretty printing that emulates the one of the database
1682
- shells. So, the same query running with the PostgreSQL adapter would yield instead</p><div class="code_container">
1683
- <pre class="brush: plain; gutter: false; toolbar: false">
1684
- EXPLAIN for: SELECT "users".* FROM "users" INNER JOIN "articles" ON "articles"."user_id" = "users"."id" WHERE "users"."id" = 1
1685
- QUERY PLAN
1686
- ------------------------------------------------------------------------------
1687
- Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
1688
- Join Filter: (articles.user_id = users.id)
1689
- -&gt; Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
1690
- Index Cond: (id = 1)
1691
- -&gt; Seq Scan on articles (cost=0.00..28.88 rows=8 width=4)
1692
- Filter: (articles.user_id = 1)
1693
- (6 rows)
1694
-
1695
- </pre>
1696
- </div>
1697
- <p>Eager loading may trigger more than one query under the hood, and some queries
1698
- may need the results of previous ones. Because of that, <code>explain</code> actually
1699
- executes the query, and then asks for the query plans. For example,</p><div class="code_container">
1700
- <pre class="brush: ruby; gutter: false; toolbar: false">
1701
- User.where(id: 1).includes(:articles).explain
1702
-
1703
- </pre>
1704
- </div>
1705
- <p>yields</p><div class="code_container">
1706
- <pre class="brush: plain; gutter: false; toolbar: false">
1707
- EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
1708
- +----+-------------+-------+-------+---------------+
1709
- | id | select_type | table | type | possible_keys |
1710
- +----+-------------+-------+-------+---------------+
1711
- | 1 | SIMPLE | users | const | PRIMARY |
1712
- +----+-------------+-------+-------+---------------+
1713
- +---------+---------+-------+------+-------+
1714
- | key | key_len | ref | rows | Extra |
1715
- +---------+---------+-------+------+-------+
1716
- | PRIMARY | 4 | const | 1 | |
1717
- +---------+---------+-------+------+-------+
1718
-
1719
- 1 row in set (0.00 sec)
1720
-
1721
- EXPLAIN for: SELECT `articles`.* FROM `articles` WHERE `articles`.`user_id` IN (1)
1722
- +----+-------------+----------+------+---------------+
1723
- | id | select_type | table | type | possible_keys |
1724
- +----+-------------+----------+------+---------------+
1725
- | 1 | SIMPLE | articles | ALL | NULL |
1726
- +----+-------------+----------+------+---------------+
1727
- +------+---------+------+------+-------------+
1728
- | key | key_len | ref | rows | Extra |
1729
- +------+---------+------+------+-------------+
1730
- | NULL | NULL | NULL | 1 | Using where |
1731
- +------+---------+------+------+-------------+
1732
-
1733
-
1734
- 1 row in set (0.00 sec)
1735
-
1736
- </pre>
1737
- </div>
1738
- <p>under MySQL.</p><h4 id="interpreting-explain">20.1 Interpreting EXPLAIN</h4><p>Interpretation of the output of EXPLAIN is beyond the scope of this guide. The
1739
- following pointers may be helpful:</p>
1740
- <ul>
1741
- <li><p>SQLite3: <a href="http://www.sqlite.org/eqp.html">EXPLAIN QUERY PLAN</a></p></li>
1742
- <li><p>MySQL: <a href="http://dev.mysql.com/doc/refman/5.6/en/explain-output.html">EXPLAIN Output Format</a></p></li>
1743
- <li><p>PostgreSQL: <a href="http://www.postgresql.org/docs/current/static/using-explain.html">Using EXPLAIN</a></p></li>
1744
- </ul>
1745
-
1746
-
1747
- <h3>Feedback</h3>
1748
- <p>
1749
- You're encouraged to help improve the quality of this guide.
1750
- </p>
1751
- <p>
1752
- Please contribute if you see any typos or factual errors.
1753
- To get started, you can read our <a href="http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section.
1754
- </p>
1755
- <p>
1756
- You may also find incomplete content, or stuff that is not up to date.
1757
- Please do add any missing documentation for master. Make sure to check
1758
- <a href="http://edgeguides.rubyonrails.org">Edge Guides</a> first to verify
1759
- if the issues are already fixed or not on the master branch.
1760
- Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
1761
- for style and conventions.
1762
- </p>
1763
- <p>
1764
- If for whatever reason you spot something to fix but cannot patch it yourself, please
1765
- <a href="https://github.com/rails/rails/issues">open an issue</a>.
1766
- </p>
1767
- <p>And last but not least, any kind of discussion regarding Ruby on Rails
1768
- documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
1769
- </p>
1770
- </div>
1771
- </div>
1772
- </div>
1773
-
1774
- <hr class="hide" />
1775
- <div id="footer">
1776
- <div class="wrapper">
1777
- <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p>
1778
- <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
1779
-
1780
- </div>
1781
- </div>
1782
-
1783
- <script type="text/javascript" src="javascripts/jquery.min.js"></script>
1784
- <script type="text/javascript" src="javascripts/responsive-tables.js"></script>
1785
- <script type="text/javascript" src="javascripts/guides.js"></script>
1786
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
1787
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
1788
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
1789
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
1790
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
1791
- <script type="text/javascript">
1792
- SyntaxHighlighter.all();
1793
- $(guidesIndex.bind);
1794
- </script>
1795
- </body>
1796
- </html>