railties 3.0.11 → 3.0.12.rc1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (166) hide show
  1. data/lib/rails/version.rb +2 -2
  2. metadata +305 -461
  3. data/guides/output/2_2_release_notes.html +0 -565
  4. data/guides/output/2_3_release_notes.html +0 -713
  5. data/guides/output/3_0_release_notes.html +0 -652
  6. data/guides/output/3_1_release_notes.html +0 -670
  7. data/guides/output/action_controller_overview.html +0 -925
  8. data/guides/output/action_mailer_basics.html +0 -658
  9. data/guides/output/action_view_overview.html +0 -1471
  10. data/guides/output/active_model_basics.html +0 -349
  11. data/guides/output/active_record_basics.html +0 -364
  12. data/guides/output/active_record_querying.html +0 -1272
  13. data/guides/output/active_record_validations_callbacks.html +0 -1292
  14. data/guides/output/active_resource_basics.html +0 -252
  15. data/guides/output/active_support_core_extensions.html +0 -3374
  16. data/guides/output/ajax_on_rails.html +0 -412
  17. data/guides/output/api_documentation_guidelines.html +0 -317
  18. data/guides/output/asset_pipeline.html +0 -691
  19. data/guides/output/association_basics.html +0 -1742
  20. data/guides/output/caching_with_rails.html +0 -533
  21. data/guides/output/command_line.html +0 -662
  22. data/guides/output/configuring.html +0 -811
  23. data/guides/output/contribute.html +0 -216
  24. data/guides/output/contributing_to_ruby_on_rails.html +0 -465
  25. data/guides/output/credits.html +0 -210
  26. data/guides/output/debugging_rails_applications.html +0 -791
  27. data/guides/output/engines.html +0 -673
  28. data/guides/output/form_helpers.html +0 -850
  29. data/guides/output/generators.html +0 -725
  30. data/guides/output/getting_started.html +0 -1980
  31. data/guides/output/i18n.html +0 -1054
  32. data/guides/output/images/belongs_to.png +0 -0
  33. data/guides/output/images/book_icon.gif +0 -0
  34. data/guides/output/images/bullet.gif +0 -0
  35. data/guides/output/images/challenge.png +0 -0
  36. data/guides/output/images/chapters_icon.gif +0 -0
  37. data/guides/output/images/check_bullet.gif +0 -0
  38. data/guides/output/images/credits_pic_blank.gif +0 -0
  39. data/guides/output/images/csrf.png +0 -0
  40. data/guides/output/images/customized_error_messages.png +0 -0
  41. data/guides/output/images/edge_badge.png +0 -0
  42. data/guides/output/images/error_messages.png +0 -0
  43. data/guides/output/images/feature_tile.gif +0 -0
  44. data/guides/output/images/footer_tile.gif +0 -0
  45. data/guides/output/images/fxn.png +0 -0
  46. data/guides/output/images/grey_bullet.gif +0 -0
  47. data/guides/output/images/habtm.png +0 -0
  48. data/guides/output/images/has_many.png +0 -0
  49. data/guides/output/images/has_many_through.png +0 -0
  50. data/guides/output/images/has_one.png +0 -0
  51. data/guides/output/images/has_one_through.png +0 -0
  52. data/guides/output/images/header_backdrop.png +0 -0
  53. data/guides/output/images/header_tile.gif +0 -0
  54. data/guides/output/images/i18n/demo_html_safe.png +0 -0
  55. data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
  56. data/guides/output/images/i18n/demo_translated_en.png +0 -0
  57. data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
  58. data/guides/output/images/i18n/demo_translation_missing.png +0 -0
  59. data/guides/output/images/i18n/demo_untranslated.png +0 -0
  60. data/guides/output/images/icons/README +0 -5
  61. data/guides/output/images/icons/callouts/1.png +0 -0
  62. data/guides/output/images/icons/callouts/10.png +0 -0
  63. data/guides/output/images/icons/callouts/11.png +0 -0
  64. data/guides/output/images/icons/callouts/12.png +0 -0
  65. data/guides/output/images/icons/callouts/13.png +0 -0
  66. data/guides/output/images/icons/callouts/14.png +0 -0
  67. data/guides/output/images/icons/callouts/15.png +0 -0
  68. data/guides/output/images/icons/callouts/2.png +0 -0
  69. data/guides/output/images/icons/callouts/3.png +0 -0
  70. data/guides/output/images/icons/callouts/4.png +0 -0
  71. data/guides/output/images/icons/callouts/5.png +0 -0
  72. data/guides/output/images/icons/callouts/6.png +0 -0
  73. data/guides/output/images/icons/callouts/7.png +0 -0
  74. data/guides/output/images/icons/callouts/8.png +0 -0
  75. data/guides/output/images/icons/callouts/9.png +0 -0
  76. data/guides/output/images/icons/caution.png +0 -0
  77. data/guides/output/images/icons/example.png +0 -0
  78. data/guides/output/images/icons/home.png +0 -0
  79. data/guides/output/images/icons/important.png +0 -0
  80. data/guides/output/images/icons/next.png +0 -0
  81. data/guides/output/images/icons/note.png +0 -0
  82. data/guides/output/images/icons/prev.png +0 -0
  83. data/guides/output/images/icons/tip.png +0 -0
  84. data/guides/output/images/icons/up.png +0 -0
  85. data/guides/output/images/icons/warning.png +0 -0
  86. data/guides/output/images/jaimeiniesta.jpg +0 -0
  87. data/guides/output/images/nav_arrow.gif +0 -0
  88. data/guides/output/images/polymorphic.png +0 -0
  89. data/guides/output/images/posts_index.png +0 -0
  90. data/guides/output/images/radar.png +0 -0
  91. data/guides/output/images/rails_guides_logo.gif +0 -0
  92. data/guides/output/images/rails_logo_remix.gif +0 -0
  93. data/guides/output/images/rails_welcome.png +0 -0
  94. data/guides/output/images/session_fixation.png +0 -0
  95. data/guides/output/images/tab_grey.gif +0 -0
  96. data/guides/output/images/tab_info.gif +0 -0
  97. data/guides/output/images/tab_note.gif +0 -0
  98. data/guides/output/images/tab_red.gif +0 -0
  99. data/guides/output/images/tab_yellow.gif +0 -0
  100. data/guides/output/images/tab_yellow.png +0 -0
  101. data/guides/output/images/validation_error_messages.png +0 -0
  102. data/guides/output/images/vijaydev.jpg +0 -0
  103. data/guides/output/index.html +0 -300
  104. data/guides/output/initialization.html +0 -1087
  105. data/guides/output/javascripts/guides.js +0 -7
  106. data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  107. data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  108. data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  109. data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  110. data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  111. data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  112. data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  113. data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  114. data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  115. data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  116. data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  117. data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  118. data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  119. data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  120. data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  121. data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  122. data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  123. data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  124. data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  125. data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  126. data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  127. data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  128. data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  129. data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  130. data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  131. data/guides/output/javascripts/syntaxhighlighter/shCore.js +0 -17
  132. data/guides/output/layout.html +0 -312
  133. data/guides/output/layouts_and_rendering.html +0 -1257
  134. data/guides/output/migrations.html +0 -751
  135. data/guides/output/nested_model_forms.html +0 -350
  136. data/guides/output/performance_testing.html +0 -858
  137. data/guides/output/plugins.html +0 -590
  138. data/guides/output/rails_application_templates.html +0 -368
  139. data/guides/output/rails_on_rack.html +0 -408
  140. data/guides/output/routing.html +0 -1246
  141. data/guides/output/ruby_on_rails_guides_guidelines.html +0 -218
  142. data/guides/output/security.html +0 -968
  143. data/guides/output/stylesheets/fixes.css +0 -16
  144. data/guides/output/stylesheets/main.css +0 -445
  145. data/guides/output/stylesheets/print.css +0 -52
  146. data/guides/output/stylesheets/reset.css +0 -43
  147. data/guides/output/stylesheets/style.css +0 -13
  148. data/guides/output/stylesheets/syntaxhighlighter/shCore.css +0 -226
  149. data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  150. data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  151. data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  152. data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  153. data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  154. data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  155. data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  156. data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  157. data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  158. data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  159. data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  160. data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  161. data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  162. data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  163. data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  164. data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  165. data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  166. data/guides/output/testing.html +0 -1182
@@ -1,1272 +0,0 @@
1
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
-
4
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5
- <head>
6
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
7
-
8
- <title>Ruby on Rails Guides: Active Record Query Interface</title>
9
-
10
- <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
11
- <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
12
-
13
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
14
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
15
-
16
- <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
17
- </head>
18
- <body class="guide">
19
- <div id="topNav">
20
- <div class="wrapper">
21
- <strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
22
- <a href="http://rubyonrails.org/">Overview</a> |
23
- <a href="http://rubyonrails.org/download">Download</a> |
24
- <a href="http://rubyonrails.org/deploy">Deploy</a> |
25
- <a href="https://github.com/rails/rails">Code</a> |
26
- <a href="http://rubyonrails.org/screencasts">Screencasts</a> |
27
- <a href="http://rubyonrails.org/documentation">Documentation</a> |
28
- <a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
29
- <a href="http://rubyonrails.org/community">Community</a> |
30
- <a href="http://weblog.rubyonrails.org/">Blog</a>
31
- </div>
32
- </div>
33
- <div id="header">
34
- <div class="wrapper clearfix">
35
- <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
36
- <p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
37
- <ul class="nav">
38
- <li><a href="index.html">Home</a></li>
39
- <li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
40
- <div id="guides" class="clearfix" style="display: none;">
41
- <hr />
42
- <dl class="L">
43
- <dt>Start Here</dt>
44
- <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
45
- <dt>Models</dt>
46
- <dd><a href="migrations.html">Rails Database Migrations</a></dd>
47
- <dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
48
- <dd><a href="association_basics.html">Active Record Associations</a></dd>
49
- <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
50
- <dt>Views</dt>
51
- <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
52
- <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
53
- <dt>Controllers</dt>
54
- <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
55
- <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
56
- </dl>
57
- <dl class="R">
58
- <dt>Digging Deeper</dt>
59
- <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
60
- <dd><a href="i18n.html">Rails Internationalization API</a></dd>
61
- <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
62
- <dd><a href="testing.html">Testing Rails Applications</a></dd>
63
- <dd><a href="security.html">Securing Rails Applications</a></dd>
64
- <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
65
- <dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
66
- <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
67
- <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
68
- <dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
69
- <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
70
-
71
- <dt>Extending Rails</dt>
72
- <dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
73
- <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
74
- <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
75
-
76
- <dt>Contributing to Ruby on Rails</dt>
77
- <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
78
- <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
79
- <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
80
-
81
- <dt>Release Notes</dt>
82
- <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
83
- <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
84
- <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
85
- <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
86
- </dl>
87
- </div>
88
- </li>
89
- <li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
90
- <li><a href="credits.html">Credits</a></li>
91
- </ul>
92
- </div>
93
- </div>
94
- <hr class="hide" />
95
-
96
- <div id="feature">
97
- <div class="wrapper">
98
- <h2>Active Record Query Interface</h2>
99
- <p>This guide covers different ways to retrieve data from the database using Active Record. By referring to this guide, you will be able to:</p>
100
- <ul>
101
- <li>Find records using a variety of methods and conditions</li>
102
- <li>Specify the order, retrieved attributes, grouping, and other properties of the found records</li>
103
- <li>Use eager loading to reduce the number of database queries needed for data retrieval</li>
104
- <li>Use dynamic finders methods</li>
105
- <li>Check for the existence of particular records</li>
106
- <li>Perform various calculations on Active Record models</li>
107
- </ul>
108
-
109
- <div id="subCol">
110
- <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
111
- <ol class="chapters">
112
- <li><a href="#retrieving-objects-from-the-database">Retrieving Objects from the Database</a><ul><li><a href="#retrieving-a-single-object">Retrieving a Single Object</a></li> <li><a href="#retrieving-multiple-objects">Retrieving Multiple Objects</a></li> <li><a href="#retrieving-multiple-objects-in-batches">Retrieving Multiple Objects in Batches</a></li></ul></li><li><a href="#conditions">Conditions</a><ul><li><a href="#pure-string-conditions">Pure String Conditions</a></li> <li><a href="#array-conditions">Array Conditions</a></li> <li><a href="#hash-conditions">Hash Conditions</a></li></ul></li><li><a href="#ordering">Ordering</a></li><li><a href="#selecting-specific-fields">Selecting Specific Fields</a></li><li><a href="#limit-and-offset">Limit and Offset</a></li><li><a href="#group">Group</a></li><li><a href="#having">Having</a></li><li><a href="#overriding-conditions">Overriding Conditions</a><ul><li><a href="#except"><tt>except</tt></a></li> <li><a href="#only"><tt>only</tt></a></li> <li><a href="#reorder"><tt>reorder</tt></a></li> <li><a href="#reverse_order"><tt>reverse_order</tt></a></li></ul></li><li><a href="#readonly-objects">Readonly Objects</a></li><li><a href="#locking-records-for-update">Locking Records for Update</a><ul><li><a href="#optimistic-locking">Optimistic Locking</a></li> <li><a href="#pessimistic-locking">Pessimistic Locking</a></li></ul></li><li><a href="#joining-tables">Joining Tables</a><ul><li><a href="#using-a-string-sql-fragment">Using a String <span class="caps">SQL</span> Fragment</a></li> <li><a href="#using-array-hash-of-named-associations">Using Array/Hash of Named Associations</a></li> <li><a href="#specifying-conditions-on-the-joined-tables">Specifying Conditions on the Joined Tables</a></li></ul></li><li><a href="#eager-loading-associations">Eager Loading Associations</a><ul><li><a href="#eager-loading-multiple-associations">Eager Loading Multiple Associations</a></li> <li><a href="#specifying-conditions-on-eager-loaded-associations">Specifying Conditions on Eager Loaded Associations</a></li></ul></li><li><a href="#scopes">Scopes</a><ul><li><a href="#working-with-times">Working with times</a></li> <li><a href="#passing-in-arguments">Passing in arguments</a></li> <li><a href="#working-with-scopes">Working with scopes</a></li> <li><a href="#applying-a-default-scope">Applying a default scope</a></li> <li><a href="#removing-all-scoping">Removing all scoping</a></li></ul></li><li><a href="#dynamic-finders">Dynamic Finders</a></li><li><a href="#find-or-build-a-new-object">Find or build a new object</a><ul><li><a href="#first_or_create"><tt>first_or_create</tt></a></li> <li><a href="#first_or_create"><tt>first_or_create!</tt></a></li> <li><a href="#first_or_initialize"><tt>first_or_initialize</tt></a></li></ul></li><li><a href="#finding-by-sql">Finding by <span class="caps">SQL</span></a></li><li><a href="#select_all"><tt>select_all</tt></a></li><li><a href="#existence-of-objects">Existence of Objects</a></li><li><a href="#calculations">Calculations</a><ul><li><a href="#count">Count</a></li> <li><a href="#average">Average</a></li> <li><a href="#minimum">Minimum</a></li> <li><a href="#maximum">Maximum</a></li> <li><a href="#sum">Sum</a></li></ul></li></ol></div>
113
- </div>
114
- </div>
115
-
116
- <div id="container">
117
- <div class="wrapper">
118
- <div id="mainCol">
119
- <div class="warning"><p>This Guide is based on Rails 3.0. Some of the code shown here will not work in other versions of Rails.</p></div>
120
- <p>If you&#8217;re used to using raw <span class="caps">SQL</span> 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 <span class="caps">SQL</span> in most cases.</p>
121
- <p>Code examples throughout this guide will refer to one or more of the following models:</p>
122
- <div class="info"><p>All of the following models use <tt>id</tt> as the primary key, unless specified otherwise.</p></div>
123
- <div class="code_container">
124
- <pre class="brush: ruby; gutter: false; toolbar: false">
125
- class Client &lt; ActiveRecord::Base
126
- has_one :address
127
- has_many :orders
128
- has_and_belongs_to_many :roles
129
- end
130
- </pre>
131
- </div>
132
- <div class="code_container">
133
- <pre class="brush: ruby; gutter: false; toolbar: false">
134
- class Address &lt; ActiveRecord::Base
135
- belongs_to :client
136
- end
137
- </pre>
138
- </div>
139
- <div class="code_container">
140
- <pre class="brush: ruby; gutter: false; toolbar: false">
141
- class Order &lt; ActiveRecord::Base
142
- belongs_to :client, :counter_cache =&gt; true
143
- end
144
- </pre>
145
- </div>
146
- <div class="code_container">
147
- <pre class="brush: ruby; gutter: false; toolbar: false">
148
- class Role &lt; ActiveRecord::Base
149
- has_and_belongs_to_many :clients
150
- end
151
- </pre>
152
- </div>
153
- <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&#8217;re using, the Active Record method format will always be the same.</p>
154
- <h3 id="retrieving-objects-from-the-database">1 Retrieving Objects from the Database</h3>
155
- <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 <span class="caps">SQL</span>.</p>
156
- <p>The methods are:</p>
157
- <ul>
158
- <li><tt>where</tt></li>
159
- <li><tt>select</tt></li>
160
- <li><tt>group</tt></li>
161
- <li><tt>order</tt></li>
162
- <li><tt>reorder</tt></li>
163
- <li><tt>reverse_order</tt></li>
164
- <li><tt>limit</tt></li>
165
- <li><tt>offset</tt></li>
166
- <li><tt>joins</tt></li>
167
- <li><tt>includes</tt></li>
168
- <li><tt>lock</tt></li>
169
- <li><tt>readonly</tt></li>
170
- <li><tt>from</tt></li>
171
- <li><tt>having</tt></li>
172
- </ul>
173
- <p>All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>.</p>
174
- <p>The primary operation of <tt>Model.find(options)</tt> can be summarized as:</p>
175
- <ul>
176
- <li>Convert the supplied options to an equivalent <span class="caps">SQL</span> query.</li>
177
- <li>Fire the <span class="caps">SQL</span> query and retrieve the corresponding results from the database.</li>
178
- <li>Instantiate the equivalent Ruby object of the appropriate model for every resulting row.</li>
179
- <li>Run <tt>after_find</tt> callbacks, if any.</li>
180
- </ul>
181
- <h4 id="retrieving-a-single-object">1.1 Retrieving a Single Object</h4>
182
- <p>Active Record provides five different ways of retrieving a single object.</p>
183
- <h5 id="using-a-primary-key">1.1.1 Using a Primary Key</h5>
184
- <p>Using <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the specified <em>primary key</em> that matches any supplied options. For example:</p>
185
- <div class="code_container">
186
- <pre class="brush: ruby; gutter: false; toolbar: false">
187
- # Find the client with primary key (id) 10.
188
- client = Client.find(10)
189
- # =&gt; #&lt;Client id: 10, first_name: &quot;Ryan&quot;&gt;
190
- </pre>
191
- </div>
192
- <p>The <span class="caps">SQL</span> equivalent of the above is:</p>
193
- <div class="code_container">
194
- <pre class="brush: sql; gutter: false; toolbar: false">
195
- SELECT * FROM clients WHERE (clients.id = 10)
196
- </pre>
197
- </div>
198
- <p><tt>Model.find(primary_key)</tt> will raise an <tt>ActiveRecord::RecordNotFound</tt> exception if no matching record is found.</p>
199
- <h5 id="first">1.1.2 <tt>first</tt></h5>
200
- <p><tt>Model.first</tt> finds the first record matched by the supplied options, if any. For example:</p>
201
- <div class="code_container">
202
- <pre class="brush: ruby; gutter: false; toolbar: false">
203
- client = Client.first
204
- # =&gt; #&lt;Client id: 1, first_name: &quot;Lifo&quot;&gt;
205
- </pre>
206
- </div>
207
- <p>The <span class="caps">SQL</span> equivalent of the above is:</p>
208
- <div class="code_container">
209
- <pre class="brush: sql; gutter: false; toolbar: false">
210
- SELECT * FROM clients LIMIT 1
211
- </pre>
212
- </div>
213
- <p><tt>Model.first</tt> returns <tt>nil</tt> if no matching record is found. No exception will be raised.</p>
214
- <h5 id="last">1.1.3 <tt>last</tt></h5>
215
- <p><tt>Model.last</tt> finds the last record matched by the supplied options. For example:</p>
216
- <div class="code_container">
217
- <pre class="brush: ruby; gutter: false; toolbar: false">
218
- client = Client.last
219
- # =&gt; #&lt;Client id: 221, first_name: &quot;Russel&quot;&gt;
220
- </pre>
221
- </div>
222
- <p>The <span class="caps">SQL</span> equivalent of the above is:</p>
223
- <div class="code_container">
224
- <pre class="brush: sql; gutter: false; toolbar: false">
225
- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
226
- </pre>
227
- </div>
228
- <p><tt>Model.last</tt> returns <tt>nil</tt> if no matching record is found. No exception will be raised.</p>
229
- <h5 id="first_1">1.1.4 <tt>first!</tt></h5>
230
- <p><tt>Model.first!</tt> finds the first record. For example:</p>
231
- <div class="code_container">
232
- <pre class="brush: ruby; gutter: false; toolbar: false">
233
- client = Client.first!
234
- # =&gt; #&lt;Client id: 1, first_name: &quot;Lifo&quot;&gt;
235
- </pre>
236
- </div>
237
- <p>The <span class="caps">SQL</span> equivalent of the above is:</p>
238
- <div class="code_container">
239
- <pre class="brush: sql; gutter: false; toolbar: false">
240
- SELECT * FROM clients LIMIT 1
241
- </pre>
242
- </div>
243
- <p><tt>Model.first!</tt> raises <tt>RecordNotFound</tt> if no matching record is found.</p>
244
- <h5 id="last_1">1.1.5 <tt>last!</tt></h5>
245
- <p><tt>Model.last!</tt> finds the last record. For example:</p>
246
- <div class="code_container">
247
- <pre class="brush: ruby; gutter: false; toolbar: false">
248
- client = Client.last!
249
- # =&gt; #&lt;Client id: 221, first_name: &quot;Russel&quot;&gt;
250
- </pre>
251
- </div>
252
- <p>The <span class="caps">SQL</span> equivalent of the above is:</p>
253
- <div class="code_container">
254
- <pre class="brush: sql; gutter: false; toolbar: false">
255
- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
256
- </pre>
257
- </div>
258
- <p><tt>Model.last!</tt> raises <tt>RecordNotFound</tt> if no matching record is found.</p>
259
- <h4 id="retrieving-multiple-objects">1.2 Retrieving Multiple Objects</h4>
260
- <h5 id="using-multiple-primary-keys">1.2.1 Using Multiple Primary Keys</h5>
261
- <p><tt>Model.find(array_of_primary_key)</tt> accepts an array of <em>primary keys</em>, returning an array containing all of the matching records for the supplied <em>primary keys</em>. For example:</p>
262
- <div class="code_container">
263
- <pre class="brush: ruby; gutter: false; toolbar: false">
264
- # Find the clients with primary keys 1 and 10.
265
- client = Client.find([1, 10]) # Or even Client.find(1, 10)
266
- # =&gt; [#&lt;Client id: 1, first_name: &quot;Lifo&quot;&gt;, #&lt;Client id: 10, first_name: &quot;Ryan&quot;&gt;]
267
- </pre>
268
- </div>
269
- <p>The <span class="caps">SQL</span> equivalent of the above is:</p>
270
- <div class="code_container">
271
- <pre class="brush: sql; gutter: false; toolbar: false">
272
- SELECT * FROM clients WHERE (clients.id IN (1,10))
273
- </pre>
274
- </div>
275
- <div class="warning"><p><tt>Model.find(array_of_primary_key)</tt> will raise an <tt>ActiveRecord::RecordNotFound</tt> exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.</p></div>
276
- <h4 id="retrieving-multiple-objects-in-batches">1.3 Retrieving Multiple Objects in Batches</h4>
277
- <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>
278
- <p>This may appear straightforward:</p>
279
- <div class="code_container">
280
- <pre class="brush: ruby; gutter: false; toolbar: false">
281
- # This is very inefficient when the users table has thousands of rows.
282
- User.all.each do |user|
283
- NewsLetter.weekly_deliver(user)
284
- end
285
- </pre>
286
- </div>
287
- <p>But this approach becomes increasingly impractical as the table size increases, since <tt>User.all.each</tt> 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>
288
- <p>Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing. The first method, <tt>find_each</tt>, retrieves a batch of records and then yields <em>each</em> record to the block individually as a model. The second method, <tt>find_in_batches</tt>, retrieves a batch of records and then yields <em>the entire batch</em> to the block as an array of models.</p>
289
- <div class="info"><p>The <tt>find_each</tt> and <tt>find_in_batches</tt> methods are intended for use in the batch processing of a large number of records that wouldn&#8217;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>
290
- <h5 id="find_each">1.3.1 <tt>find_each</tt></h5>
291
- <p>The <tt>find_each</tt> method retrieves a batch of records and then yields <em>each</em> record to the block individually as a model. In the following example, <tt>find_each</tt> will retrieve 1000 records (the current default for both <tt>find_each</tt> and <tt>find_in_batches</tt>) 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>
292
- <div class="code_container">
293
- <pre class="brush: ruby; gutter: false; toolbar: false">
294
- User.find_each do |user|
295
- NewsLetter.weekly_deliver(user)
296
- end
297
- </pre>
298
- </div>
299
- <h6 id="options-for-find_each">1.3.1.1 Options for <tt>find_each</tt></h6>
300
- <p>The <tt>find_each</tt> method accepts most of the options allowed by the regular <tt>find</tt> method, except for <tt>:order</tt> and <tt>:limit</tt>, which are reserved for internal use by <tt>find_each</tt>.</p>
301
- <p>Two additional options, <tt>:batch_size</tt> and <tt>:start</tt>, are available as well.</p>
302
- <p><strong><tt>:batch_size</tt></strong></p>
303
- <p>The <tt>:batch_size</tt> 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>
304
- <div class="code_container">
305
- <pre class="brush: ruby; gutter: false; toolbar: false">
306
- User.find_each(:batch_size =&gt; 5000) do |user|
307
- NewsLetter.weekly_deliver(user)
308
- end
309
- </pre>
310
- </div>
311
- <p><strong><tt>:start</tt></strong></p>
312
- <p>By default, records are fetched in ascending order of the primary key, which must be an integer. The <tt>:start</tt> 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>
313
- <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>
314
- <div class="code_container">
315
- <pre class="brush: ruby; gutter: false; toolbar: false">
316
- User.find_each(:start =&gt; 2000, :batch_size =&gt; 5000) do |user|
317
- NewsLetter.weekly_deliver(user)
318
- end
319
- </pre>
320
- </div>
321
- <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 <tt>:start</tt> option on each worker.</p>
322
- <div class="note"><p>The <tt>:include</tt> option allows you to name associations that should be loaded alongside with the models.</p></div>
323
- <h5 id="find_in_batches">1.3.2 <tt>find_in_batches</tt></h5>
324
- <p>The <tt>find_in_batches</tt> method is similar to <tt>find_each</tt>, since both retrieve batches of records. The difference is that <tt>find_in_batches</tt> 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>
325
- <div class="code_container">
326
- <pre class="brush: ruby; gutter: false; toolbar: false">
327
- # Give add_invoices an array of 1000 invoices at a time
328
- Invoice.find_in_batches(:include =&gt; :invoice_lines) do |invoices|
329
- export.add_invoices(invoices)
330
- end
331
- </pre>
332
- </div>
333
- <div class="note"><p>The <tt>:include</tt> option allows you to name associations that should be loaded alongside with the models.</p></div>
334
- <h6 id="options-for-find_in_batches">1.3.2.1 Options for <tt>find_in_batches</tt></h6>
335
- <p>The <tt>find_in_batches</tt> method accepts the same <tt>:batch_size</tt> and <tt>:start</tt> options as <tt>find_each</tt>, as well as most of the options allowed by the regular <tt>find</tt> method, except for <tt>:order</tt> and <tt>:limit</tt>, which are reserved for internal use by <tt>find_in_batches</tt>.</p>
336
- <h3 id="conditions">2 Conditions</h3>
337
- <p>The <tt>where</tt> method allows you to specify conditions to limit the records returned, representing the <tt>WHERE</tt>-part of the <span class="caps">SQL</span> statement. Conditions can either be specified as a string, array, or hash.</p>
338
- <h4 id="pure-string-conditions">2.1 Pure String Conditions</h4>
339
- <p>If you&#8217;d like to add conditions to your find, you could just specify them in there, just like <tt>Client.where("orders_count = '2'")</tt>. This will find all clients where the <tt>orders_count</tt> field&#8217;s value is 2.</p>
340
- <div class="warning"><p>Building your own conditions as pure strings can leave you vulnerable to <span class="caps">SQL</span> injection exploits. For example, <tt>Client.where("first_name LIKE '%#{params[:first_name]}%'")</tt> is not safe. See the next section for the preferred way to handle conditions using an array.</p></div>
341
- <h4 id="array-conditions">2.2 Array Conditions</h4>
342
- <p>Now what if that number could vary, say as an argument from somewhere? The find would then take the form:</p>
343
- <div class="code_container">
344
- <pre class="brush: ruby; gutter: false; toolbar: false">
345
- Client.where(&quot;orders_count = ?&quot;, params[:orders])
346
- </pre>
347
- </div>
348
- <p>Active Record will go through the first element in the conditions value and any additional elements will replace the question marks <tt>(?)</tt> in the first element.</p>
349
- <p>If you want to specify multiple conditions:</p>
350
- <div class="code_container">
351
- <pre class="brush: ruby; gutter: false; toolbar: false">
352
- Client.where(&quot;orders_count = ? AND locked = ?&quot;, params[:orders], false)
353
- </pre>
354
- </div>
355
- <p>In this example, the first question mark will be replaced with the value in <tt>params[:orders]</tt> and the second will be replaced with the <span class="caps">SQL</span> representation of <tt>false</tt>, which depends on the adapter.</p>
356
- <p>This code is highly preferable:</p>
357
- <div class="code_container">
358
- <pre class="brush: ruby; gutter: false; toolbar: false">
359
- Client.where(&quot;orders_count = ?&quot;, params[:orders])
360
- </pre>
361
- </div>
362
- <p>to this code:</p>
363
- <div class="code_container">
364
- <pre class="brush: ruby; gutter: false; toolbar: false">
365
- Client.where(&quot;orders_count = #{params[:orders]}&quot;)
366
- </pre>
367
- </div>
368
- <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 he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.</p>
369
- <div class="info"><p>For more information on the dangers of <span class="caps">SQL</span> injection, see the <a href="security.html#sql-injection">Ruby on Rails Security Guide</a>.</p></div>
370
- <h5 id="placeholder-conditions">2.2.1 Placeholder Conditions</h5>
371
- <p>Similar to the <tt>(?)</tt> replacement style of params, you can also specify keys/values hash in your array conditions:</p>
372
- <div class="code_container">
373
- <pre class="brush: ruby; gutter: false; toolbar: false">
374
- Client.where(&quot;created_at &gt;= :start_date AND created_at &lt;= :end_date&quot;,
375
- {:start_date =&gt; params[:start_date], :end_date =&gt; params[:end_date]})
376
- </pre>
377
- </div>
378
- <p>This makes for clearer readability if you have a large number of variable conditions.</p>
379
- <h5 id="array-range_conditions">2.2.2 Range Conditions</h5>
380
- <p>If you&#8217;re looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the <tt>IN</tt> <span class="caps">SQL</span> statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:</p>
381
- <div class="code_container">
382
- <pre class="brush: ruby; gutter: false; toolbar: false">
383
- Client.where(:created_at =&gt; (params[:start_date].to_date)..(params[:end_date].to_date))
384
- </pre>
385
- </div>
386
- <p>This query will generate something similar to the following <span class="caps">SQL</span>:</p>
387
- <div class="code_container">
388
- <pre class="brush: sql; gutter: false; toolbar: false">
389
- SELECT &quot;clients&quot;.* FROM &quot;clients&quot; WHERE (&quot;clients&quot;.&quot;created_at&quot; BETWEEN '2010-09-29' AND '2010-11-30')
390
- </pre>
391
- </div>
392
- <h4 id="hash-conditions">2.3 Hash Conditions</h4>
393
- <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>
394
- <div class="note"><p>Only equality, range and subset checking are possible with Hash conditions.</p></div>
395
- <h5 id="equality-conditions">2.3.1 Equality Conditions</h5>
396
- <div class="code_container">
397
- <pre class="brush: ruby; gutter: false; toolbar: false">
398
- Client.where(:locked =&gt; true)
399
- </pre>
400
- </div>
401
- <p>The field name can also be a string:</p>
402
- <div class="code_container">
403
- <pre class="brush: ruby; gutter: false; toolbar: false">
404
- Client.where('locked' =&gt; true)
405
- </pre>
406
- </div>
407
- <h5 id="hash-range_conditions">2.3.2 Range Conditions</h5>
408
- <p>The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section.</p>
409
- <div class="code_container">
410
- <pre class="brush: ruby; gutter: false; toolbar: false">
411
- Client.where(:created_at =&gt; (Time.now.midnight - 1.day)..Time.now.midnight)
412
- </pre>
413
- </div>
414
- <p>This will find all clients created yesterday by using a <tt>BETWEEN</tt> <span class="caps">SQL</span> statement:</p>
415
- <div class="code_container">
416
- <pre class="brush: sql; gutter: false; toolbar: false">
417
- SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
418
- </pre>
419
- </div>
420
- <p>This demonstrates a shorter syntax for the examples in <a href="#array-conditions">Array Conditions</a></p>
421
- <h5 id="subset-conditions">2.3.3 Subset Conditions</h5>
422
- <p>If you want to find records using the <tt>IN</tt> expression you can pass an array to the conditions hash:</p>
423
- <div class="code_container">
424
- <pre class="brush: ruby; gutter: false; toolbar: false">
425
- Client.where(:orders_count =&gt; [1,3,5])
426
- </pre>
427
- </div>
428
- <p>This code will generate <span class="caps">SQL</span> like this:</p>
429
- <div class="code_container">
430
- <pre class="brush: sql; gutter: false; toolbar: false">
431
- SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
432
- </pre>
433
- </div>
434
- <h3 id="ordering">3 Ordering</h3>
435
- <p>To retrieve records from the database in a specific order, you can use the <tt>order</tt> method.</p>
436
- <p>For example, if you&#8217;re getting a set of records and want to order them in ascending order by the <tt>created_at</tt> field in your table:</p>
437
- <div class="code_container">
438
- <pre class="brush: ruby; gutter: false; toolbar: false">
439
- Client.order(&quot;created_at&quot;)
440
- </pre>
441
- </div>
442
- <p>You could specify <tt>ASC</tt> or <tt>DESC</tt> as well:</p>
443
- <div class="code_container">
444
- <pre class="brush: ruby; gutter: false; toolbar: false">
445
- Client.order(&quot;created_at DESC&quot;)
446
- # OR
447
- Client.order(&quot;created_at ASC&quot;)
448
- </pre>
449
- </div>
450
- <p>Or ordering by multiple fields:</p>
451
- <div class="code_container">
452
- <pre class="brush: ruby; gutter: false; toolbar: false">
453
- Client.order(&quot;orders_count ASC, created_at DESC&quot;)
454
- </pre>
455
- </div>
456
- <h3 id="selecting-specific-fields">4 Selecting Specific Fields</h3>
457
- <p>By default, <tt>Model.find</tt> selects all the fields from the result set using <tt>select *</tt>.</p>
458
- <p>To select only a subset of fields from the result set, you can specify the subset via the <tt>select</tt> method.</p>
459
- <div class="note"><p>If the <tt>select</tt> method is used, all the returning objects will be <a href="#readonly-objects">read only</a>.</p></div>
460
- <p><br /></p>
461
- <p>For example, to select only <tt>viewable_by</tt> and <tt>locked</tt> columns:</p>
462
- <div class="code_container">
463
- <pre class="brush: ruby; gutter: false; toolbar: false">
464
- Client.select(&quot;viewable_by, locked&quot;)
465
- </pre>
466
- </div>
467
- <p>The <span class="caps">SQL</span> query used by this find call will be somewhat like:</p>
468
- <div class="code_container">
469
- <pre class="brush: sql; gutter: false; toolbar: false">
470
- SELECT viewable_by, locked FROM clients
471
- </pre>
472
- </div>
473
- <p>Be careful because this also means you&#8217;re initializing a model object with only the fields that you&#8217;ve selected. If you attempt to access a field that is not in the initialized record you&#8217;ll receive:</p>
474
- <div class="code_container">
475
- <pre class="brush: plain; gutter: false; toolbar: false">
476
- ActiveModel::MissingAttributeError: missing attribute: &lt;attribute&gt;
477
- </pre>
478
- </div>
479
- <p>Where <tt>&lt;attribute&gt;</tt> is the attribute you asked for. The <tt>id</tt> method will not raise the <tt>ActiveRecord::MissingAttributeError</tt>, so just be careful when working with associations because they need the <tt>id</tt> method to function properly.</p>
480
- <p>If you would like to only grab a single record per unique value in a certain field, you can use <tt>uniq</tt>:</p>
481
- <div class="code_container">
482
- <pre class="brush: ruby; gutter: false; toolbar: false">
483
- Client.select(:name).uniq
484
- </pre>
485
- </div>
486
- <p>This would generate <span class="caps">SQL</span> like:</p>
487
- <div class="code_container">
488
- <pre class="brush: sql; gutter: false; toolbar: false">
489
- SELECT DISTINCT name FROM clients
490
- </pre>
491
- </div>
492
- <p>You can also remove the uniqueness constraint:</p>
493
- <div class="code_container">
494
- <pre class="brush: ruby; gutter: false; toolbar: false">
495
- query = Client.select(:name).uniq
496
- # =&gt; Returns unique names
497
-
498
- query.uniq(false)
499
- # =&gt; Returns all names, even if there are duplicates
500
- </pre>
501
- </div>
502
- <h3 id="limit-and-offset">5 Limit and Offset</h3>
503
- <p>To apply <tt>LIMIT</tt> to the <span class="caps">SQL</span> fired by the <tt>Model.find</tt>, you can specify the <tt>LIMIT</tt> using <tt>limit</tt> and <tt>offset</tt> methods on the relation.</p>
504
- <p>You can use <tt>limit</tt> to specify the number of records to be retrieved, and use <tt>offset</tt> to specify the number of records to skip before starting to return the records. For example</p>
505
- <div class="code_container">
506
- <pre class="brush: ruby; gutter: false; toolbar: false">
507
- Client.limit(5)
508
- </pre>
509
- </div>
510
- <p>will return a maximum of 5 clients and because it specifies no offset it will return the first 5 in the table. The <span class="caps">SQL</span> it executes looks like this:</p>
511
- <div class="code_container">
512
- <pre class="brush: sql; gutter: false; toolbar: false">
513
- SELECT * FROM clients LIMIT 5
514
- </pre>
515
- </div>
516
- <p>Adding <tt>offset</tt> to that</p>
517
- <div class="code_container">
518
- <pre class="brush: ruby; gutter: false; toolbar: false">
519
- Client.limit(5).offset(30)
520
- </pre>
521
- </div>
522
- <p>will return instead a maximum of 5 clients beginning with the 31st. The <span class="caps">SQL</span> looks like:</p>
523
- <div class="code_container">
524
- <pre class="brush: sql; gutter: false; toolbar: false">
525
- SELECT * FROM clients LIMIT 5 OFFSET 30
526
- </pre>
527
- </div>
528
- <h3 id="group">6 Group</h3>
529
- <p>To apply a <tt>GROUP BY</tt> clause to the <span class="caps">SQL</span> fired by the finder, you can specify the <tt>group</tt> method on the find.</p>
530
- <p>For example, if you want to find a collection of the dates orders were created on:</p>
531
- <div class="code_container">
532
- <pre class="brush: ruby; gutter: false; toolbar: false">
533
- Order.select(&quot;date(created_at) as ordered_date, sum(price) as total_price&quot;).group(&quot;date(created_at)&quot;)
534
- </pre>
535
- </div>
536
- <p>And this will give you a single <tt>Order</tt> object for each date where there are orders in the database.</p>
537
- <p>The <span class="caps">SQL</span> that would be executed would be something like this:</p>
538
- <div class="code_container">
539
- <pre class="brush: sql; gutter: false; toolbar: false">
540
- SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at)
541
- </pre>
542
- </div>
543
- <h3 id="having">7 Having</h3>
544
- <p><span class="caps">SQL</span> uses the <tt>HAVING</tt> clause to specify conditions on the <tt>GROUP BY</tt> fields. You can add the <tt>HAVING</tt> clause to the <span class="caps">SQL</span> fired by the <tt>Model.find</tt> by adding the <tt>:having</tt> option to the find.</p>
545
- <p>For example:</p>
546
- <div class="code_container">
547
- <pre class="brush: ruby; gutter: false; toolbar: false">
548
- Order.select(&quot;date(created_at) as ordered_date, sum(price) as total_price&quot;).group(&quot;date(created_at)&quot;).having(&quot;sum(price) &gt; ?&quot;, 100)
549
- </pre>
550
- </div>
551
- <p>The <span class="caps">SQL</span> that would be executed would be something like this:</p>
552
- <div class="code_container">
553
- <pre class="brush: sql; gutter: false; toolbar: false">
554
- SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) HAVING sum(price) &gt; 100
555
- </pre>
556
- </div>
557
- <p>This will return single order objects for each day, but only those that are ordered more than $100 in a day.</p>
558
- <h3 id="overriding-conditions">8 Overriding Conditions</h3>
559
- <h4 id="except">8.1 <tt>except</tt></h4>
560
- <p>You can specify certain conditions to be excepted by using the <tt>except</tt> method. For example:</p>
561
- <div class="code_container">
562
- <pre class="brush: ruby; gutter: false; toolbar: false">
563
- Post.where('id &gt; 10').limit(20).order('id asc').except(:order)
564
- </pre>
565
- </div>
566
- <p>The <span class="caps">SQL</span> that would be executed:</p>
567
- <div class="code_container">
568
- <pre class="brush: sql; gutter: false; toolbar: false">
569
- SELECT * FROM posts WHERE id &gt; 10 LIMIT 20
570
- </pre>
571
- </div>
572
- <h4 id="only">8.2 <tt>only</tt></h4>
573
- <p>You can also override conditions using the <tt>only</tt> method. For example:</p>
574
- <div class="code_container">
575
- <pre class="brush: ruby; gutter: false; toolbar: false">
576
- Post.where('id &gt; 10').limit(20).order('id desc').only(:order, :where)
577
- </pre>
578
- </div>
579
- <p>The <span class="caps">SQL</span> that would be executed:</p>
580
- <div class="code_container">
581
- <pre class="brush: sql; gutter: false; toolbar: false">
582
- SELECT * FROM posts WHERE id &gt; 10 ORDER BY id DESC
583
- </pre>
584
- </div>
585
- <h4 id="reorder">8.3 <tt>reorder</tt></h4>
586
- <p>The <tt>reorder</tt> method overrides the default scope order. For example:</p>
587
- <div class="code_container">
588
- <pre class="brush: ruby; gutter: false; toolbar: false">
589
- class Post &lt; ActiveRecord::Base
590
- ..
591
- ..
592
- has_many :comments, :order =&gt; 'posted_at DESC'
593
- end
594
-
595
- Post.find(10).comments.reorder('name')
596
- </pre>
597
- </div>
598
- <p>The <span class="caps">SQL</span> that would be executed:</p>
599
- <div class="code_container">
600
- <pre class="brush: sql; gutter: false; toolbar: false">
601
- SELECT * FROM posts WHERE id = 10 ORDER BY name
602
- </pre>
603
- </div>
604
- <p>In case the <tt>reorder</tt> clause is not used, the <span class="caps">SQL</span> executed would be:</p>
605
- <div class="code_container">
606
- <pre class="brush: sql; gutter: false; toolbar: false">
607
- SELECT * FROM posts WHERE id = 10 ORDER BY posted_at DESC
608
- </pre>
609
- </div>
610
- <h4 id="reverse_order">8.4 <tt>reverse_order</tt></h4>
611
- <p>The <tt>reverse_order</tt> method reverses the ordering clause if specified.</p>
612
- <div class="code_container">
613
- <pre class="brush: ruby; gutter: false; toolbar: false">
614
- Client.where(&quot;orders_count &gt; 10&quot;).order(:name).reverse_order
615
- </pre>
616
- </div>
617
- <p>The <span class="caps">SQL</span> that would be executed:</p>
618
- <div class="code_container">
619
- <pre class="brush: sql; gutter: false; toolbar: false">
620
- SELECT * FROM clients WHERE orders_count &gt; 10 ORDER BY name DESC
621
- </pre>
622
- </div>
623
- <p>If no ordering clause is specified in the query, the <tt>reverse_order</tt> orders by the primary key in reverse order.</p>
624
- <div class="code_container">
625
- <pre class="brush: ruby; gutter: false; toolbar: false">
626
- Client.where(&quot;orders_count &gt; 10&quot;).reverse_order
627
- </pre>
628
- </div>
629
- <p>The <span class="caps">SQL</span> that would be executed:</p>
630
- <div class="code_container">
631
- <pre class="brush: sql; gutter: false; toolbar: false">
632
- SELECT * FROM clients WHERE orders_count &gt; 10 ORDER BY clients.id DESC
633
- </pre>
634
- </div>
635
- <p>This method accepts <strong>no</strong> arguments.</p>
636
- <h3 id="readonly-objects">9 Readonly Objects</h3>
637
- <p>Active Record provides <tt>readonly</tt> method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an <tt>ActiveRecord::ReadOnlyRecord</tt> exception.</p>
638
- <div class="code_container">
639
- <pre class="brush: ruby; gutter: false; toolbar: false">
640
- client = Client.readonly.first
641
- client.visits += 1
642
- client.save
643
- </pre>
644
- </div>
645
- <p>As <tt>client</tt> is explicitly set to be a readonly object, the above code will raise an <tt>ActiveRecord::ReadOnlyRecord</tt> exception when calling <tt>client.save</tt> with an updated value of <em>visits</em>.</p>
646
- <h3 id="locking-records-for-update">10 Locking Records for Update</h3>
647
- <p>Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.</p>
648
- <p>Active Record provides two locking mechanisms:</p>
649
- <ul>
650
- <li>Optimistic Locking</li>
651
- <li>Pessimistic Locking</li>
652
- </ul>
653
- <h4 id="optimistic-locking">10.1 Optimistic Locking</h4>
654
- <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 <tt>ActiveRecord::StaleObjectError</tt> exception is thrown if that has occurred and the update is ignored.</p>
655
- <p><strong>Optimistic locking column</strong></p>
656
- <p>In order to use optimistic locking, the table needs to have a column called <tt>lock_version</tt>. Each time the record is updated, Active Record increments the <tt>lock_version</tt> column. If an update request is made with a lower value in the <tt>lock_version</tt> field than is currently in the <tt>lock_version</tt> column in the database, the update request will fail with an <tt>ActiveRecord::StaleObjectError</tt>. Example:</p>
657
- <div class="code_container">
658
- <pre class="brush: ruby; gutter: false; toolbar: false">
659
- c1 = Client.find(1)
660
- c2 = Client.find(1)
661
-
662
- c1.first_name = &quot;Michael&quot;
663
- c1.save
664
-
665
- c2.name = &quot;should fail&quot;
666
- c2.save # Raises an ActiveRecord::StaleObjectError
667
- </pre>
668
- </div>
669
- <p>You&#8217;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>
670
- <div class="note"><p>You must ensure that your database schema defaults the <tt>lock_version</tt> column to <tt>0</tt>.</p></div>
671
- <p>This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.</p>
672
- <p>To override the name of the <tt>lock_version</tt> column, <tt>ActiveRecord::Base</tt> provides a class method called <tt>set_locking_column</tt>:</p>
673
- <div class="code_container">
674
- <pre class="brush: ruby; gutter: false; toolbar: false">
675
- class Client &lt; ActiveRecord::Base
676
- set_locking_column :lock_client_column
677
- end
678
- </pre>
679
- </div>
680
- <h4 id="pessimistic-locking">10.2 Pessimistic Locking</h4>
681
- <p>Pessimistic locking uses a locking mechanism provided by the underlying database. Using <tt>lock</tt> when building a relation obtains an exclusive lock on the selected rows. Relations using <tt>lock</tt> are usually wrapped inside a transaction for preventing deadlock conditions.</p>
682
- <p>For example:</p>
683
- <div class="code_container">
684
- <pre class="brush: ruby; gutter: false; toolbar: false">
685
- Item.transaction do
686
- i = Item.lock.first
687
- i.name = 'Jones'
688
- i.save
689
- end
690
- </pre>
691
- </div>
692
- <p>The above session produces the following <span class="caps">SQL</span> for a MySQL backend:</p>
693
- <div class="code_container">
694
- <pre class="brush: sql; gutter: false; toolbar: false">
695
- SQL (0.2ms) BEGIN
696
- Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
697
- Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
698
- SQL (0.8ms) COMMIT
699
- </pre>
700
- </div>
701
- <p>You can also pass raw <span class="caps">SQL</span> to the <tt>lock</tt> method for allowing different types of locks. For example, MySQL has an expression called <tt>LOCK IN SHARE MODE</tt> 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>
702
- <div class="code_container">
703
- <pre class="brush: ruby; gutter: false; toolbar: false">
704
- Item.transaction do
705
- i = Item.lock(&quot;LOCK IN SHARE MODE&quot;).find(1)
706
- i.increment!(:views)
707
- end
708
- </pre>
709
- </div>
710
- <h3 id="joining-tables">11 Joining Tables</h3>
711
- <p>Active Record provides a finder method called <tt>joins</tt> for specifying <tt>JOIN</tt> clauses on the resulting <span class="caps">SQL</span>. There are multiple ways to use the <tt>joins</tt> method.</p>
712
- <h4 id="using-a-string-sql-fragment">11.1 Using a String <span class="caps">SQL</span> Fragment</h4>
713
- <p>You can just supply the raw <span class="caps">SQL</span> specifying the <tt>JOIN</tt> clause to <tt>joins</tt>:</p>
714
- <div class="code_container">
715
- <pre class="brush: ruby; gutter: false; toolbar: false">
716
- Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
717
- </pre>
718
- </div>
719
- <p>This will result in the following <span class="caps">SQL</span>:</p>
720
- <div class="code_container">
721
- <pre class="brush: sql; gutter: false; toolbar: false">
722
- SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
723
- </pre>
724
- </div>
725
- <h4 id="using-array-hash-of-named-associations">11.2 Using Array/Hash of Named Associations</h4>
726
- <div class="warning"><p>This method only works with <tt>INNER JOIN</tt>.</p></div>
727
- <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 <tt>JOIN</tt> clause for those associations when using the <tt>joins</tt> method.</p>
728
- <p>For example, consider the following <tt>Category</tt>, <tt>Post</tt>, <tt>Comments</tt> and <tt>Guest</tt> models:</p>
729
- <div class="code_container">
730
- <pre class="brush: ruby; gutter: false; toolbar: false">
731
- class Category &lt; ActiveRecord::Base
732
- has_many :posts
733
- end
734
-
735
- class Post &lt; ActiveRecord::Base
736
- belongs_to :category
737
- has_many :comments
738
- has_many :tags
739
- end
740
-
741
- class Comment &lt; ActiveRecord::Base
742
- belongs_to :post
743
- has_one :guest
744
- end
745
-
746
- class Guest &lt; ActiveRecord::Base
747
- belongs_to :comment
748
- end
749
-
750
- class Tag &lt; ActiveRecord::Base
751
- belongs_to :post
752
- end
753
- </pre>
754
- </div>
755
- <p>Now all of the following will produce the expected join queries using <tt>INNER JOIN</tt>:</p>
756
- <h5 id="joining-a-single-association">11.2.1 Joining a Single Association</h5>
757
- <div class="code_container">
758
- <pre class="brush: ruby; gutter: false; toolbar: false">
759
- Category.joins(:posts)
760
- </pre>
761
- </div>
762
- <p>This produces:</p>
763
- <div class="code_container">
764
- <pre class="brush: sql; gutter: false; toolbar: false">
765
- SELECT categories.* FROM categories
766
- INNER JOIN posts ON posts.category_id = categories.id
767
- </pre>
768
- </div>
769
- <p>Or, in English: &#8220;return a Category object for all categories with posts&#8221;. Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:post).select(&#8220;distinct(categories.id)&#8221;).</p>
770
- <h5 id="joining-multiple-associations">11.2.2 Joining Multiple Associations</h5>
771
- <div class="code_container">
772
- <pre class="brush: ruby; gutter: false; toolbar: false">
773
- Post.joins(:category, :comments)
774
- </pre>
775
- </div>
776
- <p>This produces:</p>
777
- <div class="code_container">
778
- <pre class="brush: sql; gutter: false; toolbar: false">
779
- SELECT posts.* FROM posts
780
- INNER JOIN categories ON posts.category_id = categories.id
781
- INNER JOIN comments ON comments.post_id = posts.id
782
- </pre>
783
- </div>
784
- <p>Or, in English: &#8220;return all posts that have a category and at least one comment&#8221;. Note again that posts with multiple comments will show up multiple times.</p>
785
- <h5 id="joining-nested-associations-single-level">11.2.3 Joining Nested Associations (Single Level)</h5>
786
- <div class="code_container">
787
- <pre class="brush: ruby; gutter: false; toolbar: false">
788
- Post.joins(:comments =&gt; :guest)
789
- </pre>
790
- </div>
791
- <p>This produces:</p>
792
- <div class="code_container">
793
- <pre class="brush: sql; gutter: false; toolbar: false">
794
- SELECT posts.* FROM posts
795
- INNER JOIN comments ON comments.post_id = posts.id
796
- INNER JOIN guests ON guests.comment_id = comments.id
797
- </pre>
798
- </div>
799
- <p>Or, in English: &#8220;return all posts that have a comment made by a guest.&#8221;</p>
800
- <h5 id="joining-nested-associations-multiple-level">11.2.4 Joining Nested Associations (Multiple Level)</h5>
801
- <div class="code_container">
802
- <pre class="brush: ruby; gutter: false; toolbar: false">
803
- Category.joins(:posts =&gt; [{:comments =&gt; :guest}, :tags])
804
- </pre>
805
- </div>
806
- <p>This produces:</p>
807
- <div class="code_container">
808
- <pre class="brush: sql; gutter: false; toolbar: false">
809
- SELECT categories.* FROM categories
810
- INNER JOIN posts ON posts.category_id = categories.id
811
- INNER JOIN comments ON comments.post_id = posts.id
812
- INNER JOIN guests ON guests.comment_id = comments.id
813
- INNER JOIN tags ON tags.post_id = posts.id
814
- </pre>
815
- </div>
816
- <h4 id="specifying-conditions-on-the-joined-tables">11.3 Specifying Conditions on the Joined Tables</h4>
817
- <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>
818
- <div class="code_container">
819
- <pre class="brush: ruby; gutter: false; toolbar: false">
820
- time_range = (Time.now.midnight - 1.day)..Time.now.midnight
821
- Client.joins(:orders).where('orders.created_at' =&gt; time_range)
822
- </pre>
823
- </div>
824
- <p>An alternative and cleaner syntax is to nest the hash conditions:</p>
825
- <div class="code_container">
826
- <pre class="brush: ruby; gutter: false; toolbar: false">
827
- time_range = (Time.now.midnight - 1.day)..Time.now.midnight
828
- Client.joins(:orders).where(:orders =&gt; {:created_at =&gt; time_range})
829
- </pre>
830
- </div>
831
- <p>This will find all clients who have orders that were created yesterday, again using a <tt>BETWEEN</tt> <span class="caps">SQL</span> expression.</p>
832
- <h3 id="eager-loading-associations">12 Eager Loading Associations</h3>
833
- <p>Eager loading is the mechanism for loading the associated records of the objects returned by <tt>Model.find</tt> using as few queries as possible.</p>
834
- <p><strong>N + 1 queries problem</strong></p>
835
- <p>Consider the following code, which finds 10 clients and prints their postcodes:</p>
836
- <div class="code_container">
837
- <pre class="brush: ruby; gutter: false; toolbar: false">
838
- clients = Client.limit(10)
839
-
840
- clients.each do |client|
841
- puts client.address.postcode
842
- end
843
- </pre>
844
- </div>
845
- <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>
846
- <p><strong>Solution to N + 1 queries problem</strong></p>
847
- <p>Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the <tt>includes</tt> method of the <tt>Model.find</tt> call. With <tt>includes</tt>, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.</p>
848
- <p>Revisiting the above case, we could rewrite <tt>Client.all</tt> to use eager load addresses:</p>
849
- <div class="code_container">
850
- <pre class="brush: ruby; gutter: false; toolbar: false">
851
- clients = Client.includes(:address).limit(10)
852
-
853
- clients.each do |client|
854
- puts client.address.postcode
855
- end
856
- </pre>
857
- </div>
858
- <p>The above code will execute just <strong>2</strong> queries, as opposed to <strong>11</strong> queries in the previous case:</p>
859
- <div class="code_container">
860
- <pre class="brush: sql; gutter: false; toolbar: false">
861
- SELECT * FROM clients LIMIT 10
862
- SELECT addresses.* FROM addresses
863
- WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
864
- </pre>
865
- </div>
866
- <h4 id="eager-loading-multiple-associations">12.1 Eager Loading Multiple Associations</h4>
867
- <p>Active Record lets you eager load any number of associations with a single <tt>Model.find</tt> call by using an array, hash, or a nested hash of array/hash with the <tt>includes</tt> method.</p>
868
- <h5 id="array-of-multiple-associations">12.1.1 Array of Multiple Associations</h5>
869
- <div class="code_container">
870
- <pre class="brush: ruby; gutter: false; toolbar: false">
871
- Post.includes(:category, :comments)
872
- </pre>
873
- </div>
874
- <p>This loads all the posts and the associated category and comments for each post.</p>
875
- <h5 id="nested-associations-hash">12.1.2 Nested Associations Hash</h5>
876
- <div class="code_container">
877
- <pre class="brush: ruby; gutter: false; toolbar: false">
878
- Category.includes(:posts =&gt; [{:comments =&gt; :guest}, :tags]).find(1)
879
- </pre>
880
- </div>
881
- <p>This will find the category with id 1 and eager load all of the associated posts, the associated posts&#8217; tags and comments, and every comment&#8217;s guest association.</p>
882
- <h4 id="specifying-conditions-on-eager-loaded-associations">12.2 Specifying Conditions on Eager Loaded Associations</h4>
883
- <p>Even though Active Record lets you specify conditions on the eager loaded associations just like <tt>joins</tt>, the recommended way is to use <a href="#joining-tables">joins</a> instead.</p>
884
- <p>However if you must do this, you may use <tt>where</tt> as you would normally.</p>
885
- <div class="code_container">
886
- <pre class="brush: ruby; gutter: false; toolbar: false">
887
- Post.includes(:comments).where(&quot;comments.visible&quot;, true)
888
- </pre>
889
- </div>
890
- <p>This would generate a query which contains a <tt>LEFT OUTER JOIN</tt> whereas the <tt>joins</tt> method would generate one using the <tt>INNER JOIN</tt> function instead.</p>
891
- <div class="code_container">
892
- <pre class="brush: ruby; gutter: false; toolbar: false">
893
- SELECT &quot;posts&quot;.&quot;id&quot; AS t0_r0, ... &quot;comments&quot;.&quot;updated_at&quot; AS t1_r5 FROM &quot;posts&quot; LEFT OUTER JOIN &quot;comments&quot; ON &quot;comments&quot;.&quot;post_id&quot; = &quot;posts&quot;.&quot;id&quot; WHERE (comments.visible = 1)
894
- </pre>
895
- </div>
896
- <p>If there was no <tt>where</tt> condition, this would generate the normal set of two queries.</p>
897
- <p>If, in the case of this <tt>includes</tt> query, there were no comments for any posts, all the posts would still be loaded. By using <tt>joins</tt> (an <span class="caps">INNER</span> <span class="caps">JOIN</span>), the join conditions <strong>must</strong> match, otherwise no records will be returned.</p>
898
- <h3 id="scopes">13 Scopes</h3>
899
- <p>Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as <tt>where</tt>, <tt>joins</tt> and <tt>includes</tt>. All scope methods will return an <tt>ActiveRecord::Relation</tt> object which will allow for further methods (such as other scopes) to be called on it.</p>
900
- <p>To define a simple scope, we use the <tt>scope</tt> method inside the class, passing the ARel query that we&#8217;d like run when this scope is called:</p>
901
- <div class="code_container">
902
- <pre class="brush: ruby; gutter: false; toolbar: false">
903
- class Post &lt; ActiveRecord::Base
904
- scope :published, where(:published =&gt; true)
905
- end
906
- </pre>
907
- </div>
908
- <p>Just like before, these methods are also chainable:</p>
909
- <div class="code_container">
910
- <pre class="brush: ruby; gutter: false; toolbar: false">
911
- class Post &lt; ActiveRecord::Base
912
- scope :published, where(:published =&gt; true).joins(:category)
913
- end
914
- </pre>
915
- </div>
916
- <p>Scopes are also chainable within scopes:</p>
917
- <div class="code_container">
918
- <pre class="brush: ruby; gutter: false; toolbar: false">
919
- class Post &lt; ActiveRecord::Base
920
- scope :published, where(:published =&gt; true)
921
- scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
922
- end
923
- </pre>
924
- </div>
925
- <p>To call this <tt>published</tt> scope we can call it on either the class:</p>
926
- <div class="code_container">
927
- <pre class="brush: ruby; gutter: false; toolbar: false">
928
- Post.published # =&gt; [published posts]
929
- </pre>
930
- </div>
931
- <p>Or on an association consisting of <tt>Post</tt> objects:</p>
932
- <div class="code_container">
933
- <pre class="brush: ruby; gutter: false; toolbar: false">
934
- category = Category.first
935
- category.posts.published # =&gt; [published posts belonging to this category]
936
- </pre>
937
- </div>
938
- <h4 id="working-with-times">13.1 Working with times</h4>
939
- <p>If you&#8217;re working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time.</p>
940
- <div class="code_container">
941
- <pre class="brush: ruby; gutter: false; toolbar: false">
942
- class Post &lt; ActiveRecord::Base
943
- scope :last_week, lambda { where(&quot;created_at &lt; ?&quot;, Time.zone.now ) }
944
- end
945
- </pre>
946
- </div>
947
- <p>Without the <tt>lambda</tt>, this <tt>Time.zone.now</tt> will only be called once.</p>
948
- <h4 id="passing-in-arguments">13.2 Passing in arguments</h4>
949
- <p>When a <tt>lambda</tt> is used for a <tt>scope</tt>, it can take arguments:</p>
950
- <div class="code_container">
951
- <pre class="brush: ruby; gutter: false; toolbar: false">
952
- class Post &lt; ActiveRecord::Base
953
- scope :1_week_before, lambda { |time| where(&quot;created_at &lt; ?&quot;, time)
954
- end
955
- </pre>
956
- </div>
957
- <p>This may then be called using this:</p>
958
- <div class="code_container">
959
- <pre class="brush: ruby; gutter: false; toolbar: false">
960
- Post.1_week_before(Time.zone.now)
961
- </pre>
962
- </div>
963
- <p>However, this is just duplicating the functionality that would be provided to you by a class method.</p>
964
- <div class="code_container">
965
- <pre class="brush: ruby; gutter: false; toolbar: false">
966
- class Post &lt; ActiveRecord::Base
967
- def self.1_week_before(time)
968
- where(&quot;created_at &lt; ?&quot;, time)
969
- end
970
- end
971
- </pre>
972
- </div>
973
- <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>
974
- <div class="code_container">
975
- <pre class="brush: ruby; gutter: false; toolbar: false">
976
- category.posts.1_week_before(time)
977
- </pre>
978
- </div>
979
- <h4 id="working-with-scopes">13.3 Working with scopes</h4>
980
- <p>Where a relational object is required, the <tt>scoped</tt> method may come in handy. This will return an <tt>ActiveRecord::Relation</tt> object which can have further scoping applied to it afterwards. A place where this may come in handy is on associations</p>
981
- <div class="code_container">
982
- <pre class="brush: ruby; gutter: false; toolbar: false">
983
- client = Client.find_by_first_name(&quot;Ryan&quot;)
984
- orders = client.orders.scoped
985
- </pre>
986
- </div>
987
- <p>With this new <tt>orders</tt> object, we are able to ascertain that this object can have more scopes applied to it. For instance, if we wanted to return orders only in the last 30 days at a later point.</p>
988
- <div class="code_container">
989
- <pre class="brush: ruby; gutter: false; toolbar: false">
990
- orders.where(&quot;created_at &gt; ?&quot;, 30.days.ago)
991
- </pre>
992
- </div>
993
- <h4 id="applying-a-default-scope">13.4 Applying a default scope</h4>
994
- <p>If we wish for a scope to be applied across all queries to the model we can use the <tt>default_scope</tt> method within the model itself.</p>
995
- <div class="code_container">
996
- <pre class="brush: ruby; gutter: false; toolbar: false">
997
- class Client &lt; ActiveRecord::Base
998
- default_scope where(&quot;removed_at IS NULL&quot;)
999
- end
1000
- </pre>
1001
- </div>
1002
- <p>When queries are executed on this model, the <span class="caps">SQL</span> query will now look something like this:</p>
1003
- <div class="code_container">
1004
- <pre class="brush: sql; gutter: false; toolbar: false">
1005
- SELECT * FROM clients WHERE removed_at IS NULL
1006
- </pre>
1007
- </div>
1008
- <h4 id="removing-all-scoping">13.5 Removing all scoping</h4>
1009
- <p>If we wish to remove scoping for any reason we can use the <tt>unscoped</tt> method. This is especially useful if a <tt>default_scope</tt> is specified in the model and should not be applied for this particular query.</p>
1010
- <div class="code_container">
1011
- <pre class="brush: ruby; gutter: false; toolbar: false">
1012
- Client.unscoped.all
1013
- </pre>
1014
- </div>
1015
- <p>This method removes all scoping and will do a normal query on the table.</p>
1016
- <h3 id="dynamic-finders">14 Dynamic Finders</h3>
1017
- <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 <tt>first_name</tt> on your <tt>Client</tt> model for example, you get <tt>find_by_first_name</tt> and <tt>find_all_by_first_name</tt> for free from Active Record. If you have a <tt>locked</tt> field on the <tt>Client</tt> model, you also get <tt>find_by_locked</tt> and <tt>find_all_by_locked</tt> methods.</p>
1018
- <p>You can also use <tt>find_last_by_*</tt> methods which will find the last record matching your argument.</p>
1019
- <p>You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records, like <tt>Client.find_by_name!("Ryan")</tt></p>
1020
- <p>If you want to find both by name and locked, you can chain these finders together by simply typing &#8220;<tt>and</tt>&#8221; between the fields. For example, <tt>Client.find_by_first_name_and_locked("Ryan", true)</tt>.</p>
1021
- <div class="warning"><p>Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say <tt>Client.find_by_name_and_locked(&#8220;Ryan&#8221;)</tt>, the behavior is to pass <tt>nil</tt> as the missing argument. This is <strong>unintentional</strong> and this behavior will be changed in Rails 3.2 to throw an <tt>ArgumentError</tt>.</p></div>
1022
- <h3 id="find-or-build-a-new-object">15 Find or build a new object</h3>
1023
- <p>It&#8217;s common that you need to find a record or create it if it doesn&#8217;t exist. You can do that with the <tt>first_or_create</tt> and <tt>first_or_create!</tt> methods.</p>
1024
- <h4 id="first_or_create">15.1 <tt>first_or_create</tt></h4>
1025
- <p>The <tt>first_or_create</tt> method checks whether <tt>first</tt> returns <tt>nil</tt> or not. If it does return <tt>nil</tt>, then <tt>create</tt> is called. This is very powerful when coupled with the <tt>where</tt> method. Let&#8217;s see an example.</p>
1026
- <p>Suppose you want to find a client named &#8216;Andy&#8217;, and if there&#8217;s none, create one and additionally set his <tt>locked</tt> attribute to false. You can do so by running:</p>
1027
- <div class="code_container">
1028
- <pre class="brush: ruby; gutter: false; toolbar: false">
1029
- Client.where(:first_name =&gt; 'Andy').first_or_create(:locked =&gt; false)
1030
- # =&gt; #&lt;Client id: 1, first_name: &quot;Andy&quot;, orders_count: 0, locked: false, created_at: &quot;2011-08-30 06:09:27&quot;, updated_at: &quot;2011-08-30 06:09:27&quot;&gt;
1031
- </pre>
1032
- </div>
1033
- <p>The <span class="caps">SQL</span> generated by this method looks like this:</p>
1034
- <div class="code_container">
1035
- <pre class="brush: sql; gutter: false; toolbar: false">
1036
- SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
1037
- BEGIN
1038
- INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 0, NULL, '2011-08-30 05:22:57')
1039
- COMMIT
1040
- </pre>
1041
- </div>
1042
- <p><tt>first_or_create</tt> returns either the record that already exists or the new record. In our case, we didn&#8217;t already have a client named Andy so the record is created and returned.</p>
1043
- <p>The new record might not be saved to the database; that depends on whether validations passed or not (just like <tt>create</tt>).</p>
1044
- <p>It&#8217;s also worth noting that <tt>first_or_create</tt> takes into account the arguments of the <tt>where</tt> method. In the example above we didn&#8217;t explicitly pass a <tt>:first_name => 'Andy'</tt> argument to <tt>first_or_create</tt>. However, that was used when creating the new record because it was already passed before to the <tt>where</tt> method.</p>
1045
- <p>You can do the same with the <tt>find_or_create_by</tt> method:</p>
1046
- <div class="code_container">
1047
- <pre class="brush: ruby; gutter: false; toolbar: false">
1048
- Client.find_or_create_by_first_name(:first_name =&gt; &quot;Andy&quot;, :locked =&gt; false)
1049
- </pre>
1050
- </div>
1051
- <p>This method still works, but it&#8217;s encouraged to use <tt>first_or_create</tt> because it&#8217;s more explicit on which arguments are used to <em>find</em> the record and which are used to <em>create</em>, resulting in less confusion overall.</p>
1052
- <h4 id="first_or_create">15.2 <tt>first_or_create!</tt></h4>
1053
- <p>You can also use <tt>first_or_create!</tt> to raise an exception if the new record is invalid. Validations are not covered on this guide, but let&#8217;s assume for a moment that you temporarily add</p>
1054
- <div class="code_container">
1055
- <pre class="brush: ruby; gutter: false; toolbar: false">
1056
- validates :orders_count, :presence =&gt; true
1057
- </pre>
1058
- </div>
1059
- <p>to your <tt>Client</tt> model. If you try to create a new <tt>Client</tt> without passing an <tt>orders_count</tt>, the record will be invalid and an exception will be raised:</p>
1060
- <div class="code_container">
1061
- <pre class="brush: ruby; gutter: false; toolbar: false">
1062
- Client.where(:first_name =&gt; 'Andy').first_or_create!(:locked =&gt; false)
1063
- # =&gt; ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
1064
- </pre>
1065
- </div>
1066
- <h4 id="first_or_initialize">15.3 <tt>first_or_initialize</tt></h4>
1067
- <p>The <tt>first_or_initialize</tt> method will work just like <tt>first_or_create</tt> but it will not call <tt>create</tt> but <tt>new</tt>. This means that a new model instance will be created in memory but won&#8217;t be saved to the database. Continuing with the <tt>first_or_create</tt> example, we now want the client named &#8216;Nick&#8217;:</p>
1068
- <div class="code_container">
1069
- <pre class="brush: ruby; gutter: false; toolbar: false">
1070
- nick = Client.where(:first_name =&gt; 'Nick').first_or_initialize(:locked =&gt; false)
1071
- # =&gt; &lt;Client id: nil, first_name: &quot;Nick&quot;, orders_count: 0, locked: false, created_at: &quot;2011-08-30 06:09:27&quot;, updated_at: &quot;2011-08-30 06:09:27&quot;&gt;
1072
-
1073
- nick.persisted?
1074
- # =&gt; false
1075
-
1076
- nick.new_record?
1077
- # =&gt; true
1078
- </pre>
1079
- </div>
1080
- <p>Because the object is not yet stored in the database, the <span class="caps">SQL</span> generated looks like this:</p>
1081
- <div class="code_container">
1082
- <pre class="brush: sql; gutter: false; toolbar: false">
1083
- SELECT * FROM clients WHERE (clients.first_name = 'Nick') LIMIT 1
1084
- </pre>
1085
- </div>
1086
- <p>When you want to save it to the database, just call <tt>save</tt>:</p>
1087
- <div class="code_container">
1088
- <pre class="brush: ruby; gutter: false; toolbar: false">
1089
- nick.save
1090
- # =&gt; true
1091
- </pre>
1092
- </div>
1093
- <h3 id="finding-by-sql">16 Finding by <span class="caps">SQL</span></h3>
1094
- <p>If you&#8217;d like to use your own <span class="caps">SQL</span> to find records in a table you can use <tt>find_by_sql</tt>. The <tt>find_by_sql</tt> 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>
1095
- <div class="code_container">
1096
- <pre class="brush: ruby; gutter: false; toolbar: false">
1097
- Client.find_by_sql(&quot;SELECT * FROM clients
1098
- INNER JOIN orders ON clients.id = orders.client_id
1099
- ORDER clients.created_at desc&quot;)
1100
- </pre>
1101
- </div>
1102
- <p><tt>find_by_sql</tt> provides you with a simple way of making custom calls to the database and retrieving instantiated objects.</p>
1103
- <h3 id="select_all">17 <tt>select_all</tt></h3>
1104
- <p><tt>find_by_sql</tt> has a close relative called <tt>connection#select_all</tt>. <tt>select_all</tt> will retrieve objects from the database using custom <span class="caps">SQL</span> just like <tt>find_by_sql</tt> but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.</p>
1105
- <div class="code_container">
1106
- <pre class="brush: ruby; gutter: false; toolbar: false">
1107
- Client.connection.select_all(&quot;SELECT * FROM clients WHERE id = '1'&quot;)
1108
- </pre>
1109
- </div>
1110
- <h3 id="existence-of-objects">18 Existence of Objects</h3>
1111
- <p>If you simply want to check for the existence of the object there&#8217;s a method called <tt>exists?</tt>. This method will query the database using the same query as <tt>find</tt>, but instead of returning an object or collection of objects it will return either <tt>true</tt> or <tt>false</tt>.</p>
1112
- <div class="code_container">
1113
- <pre class="brush: ruby; gutter: false; toolbar: false">
1114
- Client.exists?(1)
1115
- </pre>
1116
- </div>
1117
- <p>The <tt>exists?</tt> method also takes multiple ids, but the catch is that it will return true if any one of those records exists.</p>
1118
- <div class="code_container">
1119
- <pre class="brush: ruby; gutter: false; toolbar: false">
1120
- Client.exists?(1,2,3)
1121
- # or
1122
- Client.exists?([1,2,3])
1123
- </pre>
1124
- </div>
1125
- <p>It&#8217;s even possible to use <tt>exists?</tt> without any arguments on a model or a relation.</p>
1126
- <div class="code_container">
1127
- <pre class="brush: ruby; gutter: false; toolbar: false">
1128
- Client.where(:first_name =&gt; 'Ryan').exists?
1129
- </pre>
1130
- </div>
1131
- <p>The above returns <tt>true</tt> if there is at least one client with the <tt>first_name</tt> &#8216;Ryan&#8217; and <tt>false</tt> otherwise.</p>
1132
- <div class="code_container">
1133
- <pre class="brush: ruby; gutter: false; toolbar: false">
1134
- Client.exists?
1135
- </pre>
1136
- </div>
1137
- <p>The above returns <tt>false</tt> if the <tt>clients</tt> table is empty and <tt>true</tt> otherwise.</p>
1138
- <p>You can also use <tt>any?</tt> and <tt>many?</tt> to check for existence on a model or relation.</p>
1139
- <div class="code_container">
1140
- <pre class="brush: ruby; gutter: false; toolbar: false">
1141
- # via a model
1142
- Post.any?
1143
- Post.many?
1144
-
1145
- # via a named scope
1146
- Post.recent.any?
1147
- Post.recent.many?
1148
-
1149
- # via a relation
1150
- Post.where(:published =&gt; true).any?
1151
- Post.where(:published =&gt; true).many?
1152
-
1153
- # via an association
1154
- Post.first.categories.any?
1155
- Post.first.categories.many?
1156
- </pre>
1157
- </div>
1158
- <h3 id="calculations">19 Calculations</h3>
1159
- <p>This section uses count as an example method in this preamble, but the options described apply to all sub-sections.</p>
1160
- <p>All calculation methods work directly on a model:</p>
1161
- <div class="code_container">
1162
- <pre class="brush: ruby; gutter: false; toolbar: false">
1163
- Client.count
1164
- # SELECT count(*) AS count_all FROM clients
1165
- </pre>
1166
- </div>
1167
- <p>Or on a relation:</p>
1168
- <div class="code_container">
1169
- <pre class="brush: ruby; gutter: false; toolbar: false">
1170
- Client.where(:first_name =&gt; 'Ryan').count
1171
- # SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
1172
- </pre>
1173
- </div>
1174
- <p>You can also use various finder methods on a relation for performing complex calculations:</p>
1175
- <div class="code_container">
1176
- <pre class="brush: ruby; gutter: false; toolbar: false">
1177
- Client.includes(&quot;orders&quot;).where(:first_name =&gt; 'Ryan', :orders =&gt; {:status =&gt; 'received'}).count
1178
- </pre>
1179
- </div>
1180
- <p>Which will execute:</p>
1181
- <div class="code_container">
1182
- <pre class="brush: sql; gutter: false; toolbar: false">
1183
- SELECT count(DISTINCT clients.id) AS count_all FROM clients
1184
- LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
1185
- (clients.first_name = 'Ryan' AND orders.status = 'received')
1186
- </pre>
1187
- </div>
1188
- <h4 id="count">19.1 Count</h4>
1189
- <p>If you want to see how many records are in your model&#8217;s table you could call <tt>Client.count</tt> 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 <tt>Client.count(:age)</tt>.</p>
1190
- <p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p>
1191
- <h4 id="average">19.2 Average</h4>
1192
- <p>If you want to see the average of a certain number in one of your tables you can call the <tt>average</tt> method on the class that relates to the table. This method call will look something like this:</p>
1193
- <div class="code_container">
1194
- <pre class="brush: ruby; gutter: false; toolbar: false">
1195
- Client.average(&quot;orders_count&quot;)
1196
- </pre>
1197
- </div>
1198
- <p>This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.</p>
1199
- <p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p>
1200
- <h4 id="minimum">19.3 Minimum</h4>
1201
- <p>If you want to find the minimum value of a field in your table you can call the <tt>minimum</tt> method on the class that relates to the table. This method call will look something like this:</p>
1202
- <div class="code_container">
1203
- <pre class="brush: ruby; gutter: false; toolbar: false">
1204
- Client.minimum(&quot;age&quot;)
1205
- </pre>
1206
- </div>
1207
- <p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p>
1208
- <h4 id="maximum">19.4 Maximum</h4>
1209
- <p>If you want to find the maximum value of a field in your table you can call the <tt>maximum</tt> method on the class that relates to the table. This method call will look something like this:</p>
1210
- <div class="code_container">
1211
- <pre class="brush: ruby; gutter: false; toolbar: false">
1212
- Client.maximum(&quot;age&quot;)
1213
- </pre>
1214
- </div>
1215
- <p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p>
1216
- <h4 id="sum">19.5 Sum</h4>
1217
- <p>If you want to find the sum of a field for all records in your table you can call the <tt>sum</tt> method on the class that relates to the table. This method call will look something like this:</p>
1218
- <div class="code_container">
1219
- <pre class="brush: ruby; gutter: false; toolbar: false">
1220
- Client.sum(&quot;orders_count&quot;)
1221
- </pre>
1222
- </div>
1223
- <p>For options, please see the parent section, <a href="#calculations">Calculations</a>.</p>
1224
-
1225
- <h3>Feedback</h3>
1226
- <p>
1227
- You're encouraged to help improve the quality of this guide.
1228
- </p>
1229
- <p>
1230
- If you see any typos or factual errors you are confident to
1231
- patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
1232
- and push the change yourself. That branch of Rails has public write access.
1233
- Commits are still reviewed, but that happens after you've submitted your
1234
- contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
1235
- cross-merged with master periodically.
1236
- </p>
1237
- <p>
1238
- You may also find incomplete content, or stuff that is not up to date.
1239
- Please do add any missing documentation for master. Check the
1240
- <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
1241
- for style and conventions.
1242
- </p>
1243
- <p>
1244
- If for whatever reason you spot something to fix but cannot patch it yourself, please
1245
- <a href="https://github.com/rails/rails/issues">open an issue</a>.
1246
- </p>
1247
- <p>And last but not least, any kind of discussion regarding Ruby on Rails
1248
- documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
1249
- </p>
1250
- </div>
1251
- </div>
1252
- </div>
1253
-
1254
- <hr class="hide" />
1255
- <div id="footer">
1256
- <div class="wrapper">
1257
- <p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
1258
- <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
1259
- </div>
1260
- </div>
1261
-
1262
- <script type="text/javascript" src="javascripts/guides.js"></script>
1263
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
1264
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
1265
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
1266
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
1267
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
1268
- <script type="text/javascript">
1269
- SyntaxHighlighter.all()
1270
- </script>
1271
- </body>
1272
- </html>