rails 4.2.11.3 → 5.0.0.beta1

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