rails_test 4.2.0.beta1

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