rails 4.2.1 → 5.1.7

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