rails 2.3.8 → 2.3.9.pre

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

Files changed (119) hide show
  1. data/CHANGELOG +3 -2
  2. data/Rakefile +6 -7
  3. data/builtin/rails_info/rails/info.rb +1 -1
  4. data/environments/boot.rb +6 -2
  5. data/environments/environment.rb +1 -1
  6. data/lib/initializer.rb +44 -20
  7. data/lib/rails/plugin.rb +1 -1
  8. data/lib/rails/plugin/loader.rb +3 -3
  9. data/lib/rails/version.rb +1 -1
  10. data/lib/rails_generator/generators/components/migration/migration_generator.rb +1 -1
  11. data/lib/rails_generator/generators/components/plugin/templates/test_helper.rb +2 -1
  12. metadata +25 -124
  13. data/guides/files/javascripts/code_highlighter.js +0 -188
  14. data/guides/files/javascripts/guides.js +0 -8
  15. data/guides/files/javascripts/highlighters.js +0 -90
  16. data/guides/files/stylesheets/main.css +0 -441
  17. data/guides/files/stylesheets/print.css +0 -52
  18. data/guides/files/stylesheets/reset.css +0 -43
  19. data/guides/files/stylesheets/style.css +0 -13
  20. data/guides/files/stylesheets/syntax.css +0 -31
  21. data/guides/images/belongs_to.png +0 -0
  22. data/guides/images/book_icon.gif +0 -0
  23. data/guides/images/bullet.gif +0 -0
  24. data/guides/images/chapters_icon.gif +0 -0
  25. data/guides/images/check_bullet.gif +0 -0
  26. data/guides/images/credits_pic_blank.gif +0 -0
  27. data/guides/images/csrf.png +0 -0
  28. data/guides/images/customized_error_messages.png +0 -0
  29. data/guides/images/error_messages.png +0 -0
  30. data/guides/images/feature_tile.gif +0 -0
  31. data/guides/images/footer_tile.gif +0 -0
  32. data/guides/images/fxn.jpg +0 -0
  33. data/guides/images/grey_bullet.gif +0 -0
  34. data/guides/images/habtm.png +0 -0
  35. data/guides/images/has_many.png +0 -0
  36. data/guides/images/has_many_through.png +0 -0
  37. data/guides/images/has_one.png +0 -0
  38. data/guides/images/has_one_through.png +0 -0
  39. data/guides/images/header_backdrop.png +0 -0
  40. data/guides/images/header_tile.gif +0 -0
  41. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  42. data/guides/images/i18n/demo_translated_en.png +0 -0
  43. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  44. data/guides/images/i18n/demo_translation_missing.png +0 -0
  45. data/guides/images/i18n/demo_untranslated.png +0 -0
  46. data/guides/images/icons/README +0 -5
  47. data/guides/images/icons/callouts/1.png +0 -0
  48. data/guides/images/icons/callouts/10.png +0 -0
  49. data/guides/images/icons/callouts/11.png +0 -0
  50. data/guides/images/icons/callouts/12.png +0 -0
  51. data/guides/images/icons/callouts/13.png +0 -0
  52. data/guides/images/icons/callouts/14.png +0 -0
  53. data/guides/images/icons/callouts/15.png +0 -0
  54. data/guides/images/icons/callouts/2.png +0 -0
  55. data/guides/images/icons/callouts/3.png +0 -0
  56. data/guides/images/icons/callouts/4.png +0 -0
  57. data/guides/images/icons/callouts/5.png +0 -0
  58. data/guides/images/icons/callouts/6.png +0 -0
  59. data/guides/images/icons/callouts/7.png +0 -0
  60. data/guides/images/icons/callouts/8.png +0 -0
  61. data/guides/images/icons/callouts/9.png +0 -0
  62. data/guides/images/icons/caution.png +0 -0
  63. data/guides/images/icons/example.png +0 -0
  64. data/guides/images/icons/home.png +0 -0
  65. data/guides/images/icons/important.png +0 -0
  66. data/guides/images/icons/next.png +0 -0
  67. data/guides/images/icons/note.png +0 -0
  68. data/guides/images/icons/prev.png +0 -0
  69. data/guides/images/icons/tip.png +0 -0
  70. data/guides/images/icons/up.png +0 -0
  71. data/guides/images/icons/warning.png +0 -0
  72. data/guides/images/nav_arrow.gif +0 -0
  73. data/guides/images/polymorphic.png +0 -0
  74. data/guides/images/posts_index.png +0 -0
  75. data/guides/images/rails_guides_logo.gif +0 -0
  76. data/guides/images/rails_logo_remix.gif +0 -0
  77. data/guides/images/rails_welcome.png +0 -0
  78. data/guides/images/session_fixation.png +0 -0
  79. data/guides/images/tab_grey.gif +0 -0
  80. data/guides/images/tab_info.gif +0 -0
  81. data/guides/images/tab_note.gif +0 -0
  82. data/guides/images/tab_red.gif +0 -0
  83. data/guides/images/tab_yellow.gif +0 -0
  84. data/guides/images/tab_yellow.png +0 -0
  85. data/guides/images/validation_error_messages.png +0 -0
  86. data/guides/rails_guides.rb +0 -42
  87. data/guides/rails_guides/generator.rb +0 -138
  88. data/guides/rails_guides/helpers.rb +0 -34
  89. data/guides/rails_guides/indexer.rb +0 -55
  90. data/guides/rails_guides/textile_extensions.rb +0 -41
  91. data/guides/source/2_2_release_notes.textile +0 -422
  92. data/guides/source/2_3_release_notes.textile +0 -610
  93. data/guides/source/action_controller_overview.textile +0 -776
  94. data/guides/source/action_mailer_basics.textile +0 -424
  95. data/guides/source/active_record_basics.textile +0 -135
  96. data/guides/source/active_record_querying.textile +0 -969
  97. data/guides/source/activerecord_validations_callbacks.textile +0 -1086
  98. data/guides/source/association_basics.textile +0 -1781
  99. data/guides/source/caching_with_rails.textile +0 -524
  100. data/guides/source/command_line.textile +0 -589
  101. data/guides/source/configuring.textile +0 -234
  102. data/guides/source/contribute.textile +0 -71
  103. data/guides/source/contributing_to_rails.textile +0 -239
  104. data/guides/source/credits.erb.textile +0 -52
  105. data/guides/source/debugging_rails_applications.textile +0 -709
  106. data/guides/source/form_helpers.textile +0 -766
  107. data/guides/source/getting_started.textile +0 -1297
  108. data/guides/source/i18n.textile +0 -912
  109. data/guides/source/index.erb.textile +0 -124
  110. data/guides/source/layout.html.erb +0 -103
  111. data/guides/source/layouts_and_rendering.textile +0 -979
  112. data/guides/source/migrations.textile +0 -591
  113. data/guides/source/nested_model_forms.textile +0 -222
  114. data/guides/source/performance_testing.textile +0 -531
  115. data/guides/source/plugins.textile +0 -1512
  116. data/guides/source/rails_on_rack.textile +0 -309
  117. data/guides/source/routing.textile +0 -903
  118. data/guides/source/security.textile +0 -986
  119. data/guides/source/testing.textile +0 -951
@@ -1,969 +0,0 @@
1
- h2. Active Record Query Interface
2
-
3
- This guide covers different ways to retrieve data from the database using Active Record. By referring to this guide, you will be able to:
4
-
5
- * Find records using a variety of methods and conditions
6
- * Specify the order, retrieved attributes, grouping, and other properties of the found records
7
- * Use eager loading to reduce the number of database queries needed for data retrieval
8
- * Use dynamic finders methods
9
- * Create named scopes to add custom finding behavior to your models
10
- * Check for the existence of particular records
11
- * Perform various calculations on Active Record models
12
-
13
- endprologue.
14
-
15
- If you're used to using raw SQL to find database records then, generally, you will 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.
16
-
17
- Code examples throughout this guide will refer to one or more of the following models:
18
-
19
- TIP: All of the following models uses +id+ as the primary key, unless specified otherwise.
20
-
21
- <br />
22
-
23
- <ruby>
24
- class Client < ActiveRecord::Base
25
- has_one :address
26
- has_one :mailing_address
27
- has_many :orders
28
- has_and_belongs_to_many :roles
29
- end
30
- </ruby>
31
-
32
- <ruby>
33
- class Address < ActiveRecord::Base
34
- belongs_to :client
35
- end
36
- </ruby>
37
-
38
- <ruby>
39
- class MailingAddress < Address
40
- end
41
- </ruby>
42
-
43
- <ruby>
44
- class Order < ActiveRecord::Base
45
- belongs_to :client, :counter_cache => true
46
- end
47
- </ruby>
48
-
49
- <ruby>
50
- class Role < ActiveRecord::Base
51
- has_and_belongs_to_many :clients
52
- end
53
- </ruby>
54
-
55
- 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.
56
-
57
- h3. Retrieving Objects from the Database
58
-
59
- To retrieve objects from the database, Active Record provides a class method called +Model.find+. This method allows you to pass arguments into it to perform certain queries on your database without the need of writing raw SQL.
60
-
61
- Primary operation of <tt>Model.find(options)</tt> can be summarized as:
62
-
63
- * Convert the supplied options to an equivalent SQL query.
64
- * Fire the SQL query and retrieve the corresponding results from the database.
65
- * Instantiate the equivalent Ruby object of the appropriate model for every resulting row.
66
- * Run +after_find+ callbacks if any.
67
-
68
- h4. Retrieving a Single Object
69
-
70
- Active Record lets you retrieve a single object using three different ways.
71
-
72
- h5. Using a Primary Key
73
-
74
- Using <tt>Model.find(primary_key, options = nil)</tt>, you can retrieve the object corresponding to the supplied _primary key_ and matching the supplied options (if any). For example:
75
-
76
- <ruby>
77
- # Find the client with primary key (id) 10.
78
- client = Client.find(10)
79
- => #<Client id: 10, name: => "Ryan">
80
- </ruby>
81
-
82
- SQL equivalent of the above is:
83
-
84
- <sql>
85
- SELECT * FROM clients WHERE (clients.id = 10)
86
- </sql>
87
-
88
- <tt>Model.find(primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception if no matching record is found.
89
-
90
- h5. +first+
91
-
92
- <tt>Model.first(options = nil)</tt> finds the first record matched by the supplied options. If no +options+ are supplied, the first matching record is returned. For example:
93
-
94
- <ruby>
95
- client = Client.first
96
- => #<Client id: 1, name: => "Lifo">
97
- </ruby>
98
-
99
- SQL equivalent of the above is:
100
-
101
- <sql>
102
- SELECT * FROM clients LIMIT 1
103
- </sql>
104
-
105
- <tt>Model.first</tt> returns +nil+ if no matching record is found. No exception will be raised.
106
-
107
- NOTE: +Model.find(:first, options)+ is equivalent to +Model.first(options)+
108
-
109
- h5. +last+
110
-
111
- <tt>Model.last(options = nil)</tt> finds the last record matched by the supplied options. If no +options+ are supplied, the last matching record is returned. For example:
112
-
113
- <ruby>
114
- # Find the client with primary key (id) 10.
115
- client = Client.last
116
- => #<Client id: 221, name: => "Russel">
117
- </ruby>
118
-
119
- SQL equivalent of the above is:
120
-
121
- <sql>
122
- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
123
- </sql>
124
-
125
- <tt>Model.last</tt> returns +nil+ if no matching record is found. No exception will be raised.
126
-
127
- NOTE: +Model.find(:last, options)+ is equivalent to +Model.last(options)+
128
-
129
- h4. Retrieving Multiple Objects
130
-
131
- h5. Using Multiple Primary Keys
132
-
133
- <tt>Model.find(array_of_primary_key, options = nil)</tt> also accepts an array of _primary keys_. An array of all the matching records for the supplied _primary keys_ is returned. For example:
134
-
135
- <ruby>
136
- # Find the clients with primary keys 1 and 10.
137
- client = Client.find(1, 10) # Or even Client.find([1, 10])
138
- => [#<Client id: 1, name: => "Lifo">, #<Client id: 10, name: => "Ryan">]
139
- </ruby>
140
-
141
- SQL equivalent of the above is:
142
-
143
- <sql>
144
- SELECT * FROM clients WHERE (clients.id IN (1,10))
145
- </sql>
146
-
147
- <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
148
-
149
- h5. Find all
150
-
151
- <tt>Model.all(options = nil)</tt> finds all the records matching the supplied +options+. If no +options+ are supplied, all rows from the database are returned.
152
-
153
- <ruby>
154
- # Find all the clients.
155
- clients = Client.all
156
- => [#<Client id: 1, name: => "Lifo">, #<Client id: 10, name: => "Ryan">, #<Client id: 221, name: => "Russel">]
157
- </ruby>
158
-
159
- And the equivalent SQL is:
160
-
161
- <sql>
162
- SELECT * FROM clients
163
- </sql>
164
-
165
- <tt>Model.all</tt> returns an empty array +[]+ if no matching record is found. No exception will be raised.
166
-
167
- NOTE: +Model.find(:all, options)+ is equivalent to +Model.all(options)+
168
-
169
- h4. Retrieving Multiple Objects in Batches
170
-
171
- Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc.
172
-
173
- The following may seem very straight forward at first:
174
-
175
- <ruby>
176
- # Very inefficient when users table has thousands of rows.
177
- User.all.each do |user|
178
- NewsLetter.weekly_deliver(user)
179
- end
180
- </ruby>
181
-
182
- But if the total number of rows in the table is very large, the above approach may vary from being under performant to just plain impossible.
183
-
184
- This is because +User.all+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array in the memory. Sometimes that is just too many objects and demands too much memory.
185
-
186
- h5. +find_each+
187
-
188
- To efficiently iterate over a large table, Active Record provides a batch finder method called +find_each+:
189
-
190
- <ruby>
191
- User.find_each do |user|
192
- NewsLetter.weekly_deliver(user)
193
- end
194
- </ruby>
195
-
196
- *Configuring the batch size*
197
-
198
- Behind the scenes +find_each+ fetches rows in batches of +1000+ and yields them one by one. The size of the underlying batches is configurable via the +:batch_size+ option.
199
-
200
- To fetch +User+ records in batch size of +5000+:
201
-
202
- <ruby>
203
- User.find_each(:batch_size => 5000) do |user|
204
- NewsLetter.weekly_deliver(user)
205
- end
206
- </ruby>
207
-
208
- *Starting batch find from a specific primary key*
209
-
210
- Records are fetched in ascending order on the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence if the lowest is not the one you need. This may be useful for example to be able to resume an interrupted batch process if it saves the last processed ID as a checkpoint.
211
-
212
- To send newsletters only to users with the primary key starting from +2000+:
213
-
214
- <ruby>
215
- User.find_each(:batch_size => 5000, :start => 2000) do |user|
216
- NewsLetter.weekly_deliver(user)
217
- end
218
- </ruby>
219
-
220
- *Additional options*
221
-
222
- +find_each+ accepts the same options as the regular +find+ method. However, +:order+ and +:limit+ are needed internally and hence not allowed to be passed explicitly.
223
-
224
- h5. +find_in_batches+
225
-
226
- You can also work by chunks instead of row by row using +find_in_batches+. This method is analogous to +find_each+, but it yields arrays of models instead:
227
-
228
- <ruby>
229
- # Works in chunks of 1000 invoices at a time.
230
- Invoice.find_in_batches(:include => :invoice_lines) do |invoices|
231
- export.add_invoices(invoices)
232
- end
233
- </ruby>
234
-
235
- The above will yield the supplied block with +1000+ invoices every time.
236
-
237
- h3. Conditions
238
-
239
- The +find+ 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.
240
-
241
- h4. Pure String Conditions
242
-
243
- If you'd like to add conditions to your find, you could just specify them in there, just like +Client.first(:conditions => "orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2.
244
-
245
- WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.first(:conditions => "name LIKE '%#{params[:name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array.
246
-
247
- h4. Array Conditions
248
-
249
- Now what if that number could vary, say as a argument from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like:
250
-
251
- <ruby>
252
- Client.first(:conditions => ["orders_count = ?", params[:orders]])
253
- </ruby>
254
-
255
- 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.
256
-
257
- Or if you want to specify two conditions, you can do it like:
258
-
259
- <ruby>
260
- Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])
261
- </ruby>
262
-
263
- 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.
264
-
265
- The reason for doing code like:
266
-
267
- <ruby>
268
- Client.first(:conditions => ["orders_count = ?", params[:orders]])
269
- </ruby>
270
-
271
- instead of:
272
-
273
- <ruby>
274
- Client.first(:conditions => "orders_count = #{params[:orders]}")
275
- </ruby>
276
-
277
- is 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 he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.
278
-
279
- TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection.
280
-
281
- h5. Placeholder Conditions
282
-
283
- Similar to the +(?)+ replacement style of params, you can also specify keys/values hash in your array conditions:
284
-
285
- <ruby>
286
- Client.all(:conditions =>
287
- ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])
288
- </ruby>
289
-
290
- This makes for clearer readability if you have a large number of variable conditions.
291
-
292
- h5. Range Conditions
293
-
294
- If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the +IN+ SQL statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:
295
-
296
- <ruby>
297
- Client.all(:conditions => ["created_at IN (?)",
298
- (params[:start_date].to_date)..(params[:end_date].to_date)])
299
- </ruby>
300
-
301
- This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.
302
-
303
- <sql>
304
- SELECT * FROM users WHERE (created_at IN
305
- ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05',
306
- '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11',
307
- '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17',
308
- '2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
309
- ‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20',
310
- '2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26',
311
- '2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
312
- </sql>
313
-
314
- h5. Time and Date Conditions
315
-
316
- Things can get *really* messy if you pass in Time objects as it will attempt to compare your field to *every second* in that range:
317
-
318
- <ruby>
319
- Client.all(:conditions => ["created_at IN (?)",
320
- (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
321
- </ruby>
322
-
323
- <sql>
324
- SELECT * FROM users WHERE (created_at IN
325
- ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ...
326
- '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
327
- </sql>
328
-
329
- This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
330
-
331
- <shell>
332
- Got a packet bigger than 'max_allowed_packet' bytes: _query_
333
- </shell>
334
-
335
- Where _query_ is the actual query used to get that error.
336
-
337
- In this example it would be better to use greater-than and less-than operators in SQL, like so:
338
-
339
- <ruby>
340
- Client.all(:conditions =>
341
- ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
342
- </ruby>
343
-
344
- You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:
345
-
346
- <ruby>
347
- Client.all(:conditions =>
348
- ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
349
- </ruby>
350
-
351
- Just like in Ruby. If you want a shorter syntax be sure to check out the "Hash Conditions":#hash-conditions section later on in the guide.
352
-
353
- h4. Hash Conditions
354
-
355
- Active Record also allows you to pass in a 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:
356
-
357
- NOTE: Only equality, range and subset checking are possible with Hash conditions.
358
-
359
- h5. Equality Conditions
360
-
361
- <ruby>
362
- Client.all(:conditions => { :locked => true })
363
- </ruby>
364
-
365
- The field name does not have to be a symbol it can also be a string:
366
-
367
- <ruby>
368
- Client.all(:conditions => { 'locked' => true })
369
- </ruby>
370
-
371
- h5. Range Conditions
372
-
373
- The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section.
374
-
375
- <ruby>
376
- Client.all(:conditions => { :created_at => (Time.now.midnight - 1.day)..Time.now.midnight})
377
- </ruby>
378
-
379
- This will find all clients created yesterday by using a +BETWEEN+ SQL statement:
380
-
381
- <sql>
382
- SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
383
- </sql>
384
-
385
- This demonstrates a shorter syntax for the examples in "Array Conditions":#array-conditions
386
-
387
- h5. Subset Conditions
388
-
389
- If you want to find records using the +IN+ expression you can pass an array to the conditions hash:
390
-
391
- <ruby>
392
- Client.all(:conditions => { :orders_count => [1,3,5] })
393
- </ruby>
394
-
395
- This code will generate SQL like this:
396
-
397
- <sql>
398
- SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
399
- </sql>
400
-
401
- h3. Find Options
402
-
403
- Apart from +:conditions+, +Model.find+ takes a variety of other options via the options hash for customizing the resulting record set.
404
-
405
- <ruby>
406
- Model.find(id_or_array_of_ids, options_hash)
407
- Model.find(:last, options_hash)
408
- Model.find(:first, options_hash)
409
-
410
- Model.first(options_hash)
411
- Model.last(options_hash)
412
- Model.all(options_hash)
413
- </ruby>
414
-
415
- The following sections give a top level overview of all the possible keys for the +options_hash+.
416
-
417
- h4. Ordering
418
-
419
- To retrieve records from the database in a specific order, you can specify the +:order+ option to the +find+ call.
420
-
421
- 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:
422
-
423
- <ruby>
424
- Client.all(:order => "created_at")
425
- </ruby>
426
-
427
- You could specify +ASC+ or +DESC+ as well:
428
-
429
- <ruby>
430
- Client.all(:order => "created_at DESC")
431
- # OR
432
- Client.all(:order => "created_at ASC")
433
- </ruby>
434
-
435
- Or ordering by multiple fields:
436
-
437
- <ruby>
438
- Client.all(:order => "orders_count ASC, created_at DESC")
439
- </ruby>
440
-
441
- h4. Selecting Specific Fields
442
-
443
- By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
444
-
445
- To select only a subset of fields from the result set, you can specify the subset via +:select+ option on the +find+.
446
-
447
- NOTE: If the +:select+ option is used, all the returning objects will be "read only":#readonly-objects.
448
-
449
- <br />
450
-
451
- For example, to select only +viewable_by+ and +locked+ columns:
452
-
453
- <ruby>
454
- Client.all(:select => "viewable_by, locked")
455
- </ruby>
456
-
457
- The SQL query used by this find call will be somewhat like:
458
-
459
- <sql>
460
- SELECT viewable_by, locked FROM clients
461
- </sql>
462
-
463
- 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:
464
-
465
- <shell>
466
- ActiveRecord::MissingAttributeError: missing attribute: <attribute>
467
- </shell>
468
-
469
- 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.
470
-
471
- You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the +DISTINCT+ function you can do it like this:
472
-
473
- <ruby>
474
- Client.all(:select => "DISTINCT(name)")
475
- </ruby>
476
-
477
- h4. Limit and Offset
478
-
479
- To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +:limit+ and +:offset+ options on the find.
480
-
481
- If you want to limit the amount of records to a certain subset of all the records retrieved you usually use +:limit+ for this, sometimes coupled with +:offset+. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. For example:
482
-
483
- <ruby>
484
- Client.all(:limit => 5)
485
- </ruby>
486
-
487
- This code will return a maximum of 5 clients and because it specifies no offset it will return the first 5 clients in the table. The SQL it executes will look like this:
488
-
489
- <sql>
490
- SELECT * FROM clients LIMIT 5
491
- </sql>
492
-
493
- Or specifying both +:limit+ and +:offset+:
494
-
495
- <ruby>
496
- Client.all(:limit => 5, :offset => 5)
497
- </ruby>
498
-
499
- This code will return a maximum of 5 clients and because it specifies an offset this time, it will return these records starting from the 5th client in the clients table. The SQL looks like:
500
-
501
- <sql>
502
- SELECT * FROM clients LIMIT 5, 5
503
- </sql>
504
-
505
- h4. Group
506
-
507
- To apply +GROUP BY+ clause to the SQL fired by the +Model.find+, you can specify the +:group+ option on the find.
508
-
509
- For example, if you want to find a collection of the dates orders were created on:
510
-
511
- <ruby>
512
- Order.all(:group => "date(created_at)", :order => "created_at")
513
- </ruby>
514
-
515
- And this will give you a single +Order+ object for each date where there are orders in the database.
516
-
517
- The SQL that would be executed would be something like this:
518
-
519
- <sql>
520
- SELECT * FROM orders GROUP BY date(created_at)
521
- </sql>
522
-
523
- h4. Having
524
-
525
- SQL uses +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can specify the +HAVING+ clause to the SQL fired by the +Model.find+ using +:having+ option on the find.
526
-
527
- For example:
528
-
529
- <ruby>
530
- Order.all(:group => "date(created_at)", :having => ["created_at > ?", 1.month.ago])
531
- </ruby>
532
-
533
- The SQL that would be executed would be something like this:
534
-
535
- <sql>
536
- SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15'
537
- </sql>
538
-
539
- This will return single order objects for each day, but only for the last month.
540
-
541
- h4. Readonly Objects
542
-
543
- To explicitly disallow modification/destroyal of the matching records returned by +Model.find+, you could specify the +:readonly+ option as +true+ to the find call.
544
-
545
- Any attempt to alter or destroy the readonly records will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. To set this option, specify it like this:
546
-
547
- <ruby>
548
- Client.first(:readonly => true)
549
- </ruby>
550
-
551
- If you assign this record to a variable client, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
552
-
553
- <ruby>
554
- client = Client.first(:readonly => true)
555
- client.locked = false
556
- client.save
557
- </ruby>
558
-
559
- h4. Locking Records for Update
560
-
561
- Locking is helpful for preventing the race conditions when updating records in the database and ensuring atomic updated. Active Record provides two locking mechanism:
562
-
563
- * Optimistic Locking
564
- * Pessimistic Locking
565
-
566
- h5. Optimistic Locking
567
-
568
- 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.
569
-
570
- <strong>Optimistic locking column</strong>
571
-
572
- In order to use optimistic locking, the table needs to have a column called +lock_version+. Each time the record is updated, Active Record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice will let the last one saved raise an +ActiveRecord::StaleObjectError+ exception if the first was also updated. Example:
573
-
574
- <ruby>
575
- c1 = Client.find(1)
576
- c2 = Client.find(1)
577
-
578
- c1.name = "Michael"
579
- c1.save
580
-
581
- c2.name = "should fail"
582
- c2.save # Raises a ActiveRecord::StaleObjectError
583
- </ruby>
584
-
585
- 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.
586
-
587
- NOTE: You must ensure that your database schema defaults the +lock_version+ column to +0+.
588
-
589
- <br />
590
-
591
- This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
592
-
593
- To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class method called +set_locking_column+:
594
-
595
- <ruby>
596
- class Client < ActiveRecord::Base
597
- set_locking_column :lock_client_column
598
- end
599
- </ruby>
600
-
601
- h5. Pessimistic Locking
602
-
603
- Pessimistic locking uses locking mechanism provided by the underlying database. Passing +:lock => true+ to +Model.find+ obtains an exclusive lock on the selected rows. +Model.find+ using +:lock+ are usually wrapped inside a transaction for preventing deadlock conditions.
604
-
605
- For example:
606
-
607
- <ruby>
608
- Item.transaction do
609
- i = Item.first(:lock => true)
610
- i.name = 'Jones'
611
- i.save
612
- end
613
- </ruby>
614
-
615
- The above session produces the following SQL for a MySQL backend:
616
-
617
- <sql>
618
- SQL (0.2ms) BEGIN
619
- Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
620
- Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
621
- SQL (0.8ms) COMMIT
622
- </sql>
623
-
624
- You can also pass raw SQL to the +:lock+ option to allow 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:
625
-
626
- <ruby>
627
- Item.transaction do
628
- i = Item.find(1, :lock => "LOCK IN SHARE MODE")
629
- i.increment!(:views)
630
- end
631
- </ruby>
632
-
633
- h3. Joining Tables
634
-
635
- <tt>Model.find</tt> provides a +:joins+ option for specifying +JOIN+ clauses on the resulting SQL. There multiple different ways to specify the +:joins+ option:
636
-
637
- h4. Using a String SQL Fragment
638
-
639
- You can just supply the raw SQL specifying the +JOIN+ clause to the +:joins+ option. For example:
640
-
641
- <ruby>
642
- Client.all(:joins => 'LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
643
- </ruby>
644
-
645
- This will result in the following SQL:
646
-
647
- <sql>
648
- SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
649
- </sql>
650
-
651
- h4. Using Array/Hash of Named Associations
652
-
653
- WARNING: This method only works with +INNER JOIN+,
654
-
655
- <br />
656
-
657
- Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying the +:joins+ option.
658
-
659
- For example, consider the following +Category+, +Post+, +Comments+ and +Guest+ models:
660
-
661
- <ruby>
662
- class Category < ActiveRecord::Base
663
- has_many :posts
664
- end
665
-
666
- class Post < ActiveRecord::Base
667
- belongs_to :category
668
- has_many :comments
669
- has_many :tags
670
- end
671
-
672
- class Comments < ActiveRecord::Base
673
- belongs_to :post
674
- has_one :guest
675
- end
676
-
677
- class Guest < ActiveRecord::Base
678
- belongs_to :comment
679
- end
680
- </ruby>
681
-
682
- Now all of the following will produce the expected join queries using +INNER JOIN+:
683
-
684
- h5. Joining a Single Association
685
-
686
- <ruby>
687
- Category.all :joins => :posts
688
- </ruby>
689
-
690
- This produces:
691
-
692
- <sql>
693
- SELECT categories.* FROM categories
694
- INNER JOIN posts ON posts.category_id = categories.id
695
- </sql>
696
-
697
- h5. Joining Multiple Associations
698
-
699
- <ruby>
700
- Post.all :joins => [:category, :comments]
701
- </ruby>
702
-
703
- This produces:
704
-
705
- <sql>
706
- SELECT posts.* FROM posts
707
- INNER JOIN categories ON posts.category_id = categories.id
708
- INNER JOIN comments ON comments.post_id = posts.id
709
- </sql>
710
-
711
- h5. Joining Nested Associations (Single Level)
712
-
713
- <ruby>
714
- Post.all :joins => {:comments => :guest}
715
- </ruby>
716
-
717
- h5. Joining Nested Associations (Multiple Level)
718
-
719
- <ruby>
720
- Category.all :joins => {:posts => [{:comments => :guest}, :tags]}
721
- </ruby>
722
-
723
- h4. Specifying Conditions on the Joined Tables
724
-
725
- 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:
726
-
727
- <ruby>
728
- time_range = (Time.now.midnight - 1.day)..Time.now.midnight
729
- Client.all :joins => :orders, :conditions => {'orders.created_at' => time_range}
730
- </ruby>
731
-
732
- An alternative and cleaner syntax to this is to nest the hash conditions:
733
-
734
- <ruby>
735
- time_range = (Time.now.midnight - 1.day)..Time.now.midnight
736
- Client.all :joins => :orders, :conditions => {:orders => {:created_at => time_range}}
737
- </ruby>
738
-
739
- This will find all clients who have orders that were created yesterday, again using a +BETWEEN+ SQL expression.
740
-
741
- h3. Eager Loading Associations
742
-
743
- Eager loading is the mechanism for loading the associated records of the objects returned by +Model.find+ using as few queries as possible.
744
-
745
- <strong>N <plus> 1 queries problem</strong>
746
-
747
- Consider the following code, which finds 10 clients and prints their postcodes:
748
-
749
- <ruby>
750
- clients = Client.all(:limit => 10)
751
-
752
- clients.each do |client|
753
- puts client.address.postcode
754
- end
755
- </ruby>
756
-
757
- 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 ) <plus> 10 ( one per each client to load the address ) = <strong>11</strong> queries in total.
758
-
759
- <strong>Solution to N <plus> 1 queries problem</strong>
760
-
761
- Active Record lets you specify all the associations in advanced that are going to be loaded. This is possible by specifying the +:include+ option of the +Model.find+ call. By +:include+, Active Record ensures that all the specified associations are loaded using minimum possible number of queries.
762
-
763
- Revisiting the above case, we could rewrite +Client.all+ to use eager load addresses:
764
-
765
- <ruby>
766
- clients = Client.all(:include => :address, :limit => 10)
767
-
768
- clients.each do |client|
769
- puts client.address.postcode
770
- end
771
- </ruby>
772
-
773
- The above code will execute just <strong>2</strong> queries, as opposed to <strong>11</strong> queries in the previous case:
774
-
775
- <sql>
776
- SELECT * FROM clients
777
- SELECT addresses.* FROM addresses
778
- WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
779
- </sql>
780
-
781
- h4. Eager Loading Multiple Associations
782
-
783
- Active Record lets you eager load any possible number of associations with a single +Model.find+ call by using an array, hash, or a nested hash of array/hash with the +:include+ option.
784
-
785
- h5. Array of Multiple Associations
786
-
787
- <ruby>
788
- Post.all :include => [:category, :comments]
789
- </ruby>
790
-
791
- This loads all the posts and the associated category and comments for each post.
792
-
793
- h5. Nested Associations Hash
794
-
795
- <ruby>
796
- Category.find 1, :include => {:posts => [{:comments => :guest}, :tags]}
797
- </ruby>
798
-
799
- The above code finds the category with id 1 and eager loads all the posts associated with the found category. Additionally, it will also eager load every posts' tags and comments. Every comment's guest association will get eager loaded as well.
800
-
801
- h4. Specifying Conditions on Eager Loaded Associations
802
-
803
- 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.
804
-
805
- h3. Dynamic Finders
806
-
807
- 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 +name+ on your +Client+ model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+.
808
-
809
- You can do +find_last_by_*+ methods too which will find the last record matching your argument.
810
-
811
- 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")+
812
-
813
- 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_name_and_locked("Ryan", true)+.
814
-
815
-
816
- There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name("Ryan")+:
817
-
818
- <sql>
819
- SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1
820
- BEGIN
821
- INSERT INTO clients (name, updated_at, created_at, orders_count, locked)
822
- VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', 0, '0')
823
- COMMIT
824
- </sql>
825
-
826
- +find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similar to calling +new+ with the arguments you passed in. For example:
827
-
828
- <ruby>
829
- client = Client.find_or_initialize_by_name('Ryan')
830
- </ruby>
831
-
832
- will either assign an existing client object with the name "Ryan" to the client local variable, or initialize a new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it.
833
-
834
- h3. Finding by SQL
835
-
836
- 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 the underlying query returns just a single record. For example you could run this query:
837
-
838
- <ruby>
839
- Client.find_by_sql("SELECT * FROM clients
840
- INNER JOIN orders ON clients.id = orders.client_id
841
- ORDER clients.created_at desc")
842
- </ruby>
843
-
844
- +find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
845
-
846
- h3. +select_all+
847
-
848
- <tt>find_by_sql</tt> 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.
849
-
850
- <ruby>
851
- Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
852
- </ruby>
853
-
854
- h3. Existence of Objects
855
-
856
- If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as +find+, but instead of returning an object or collection of objects it will return either +true+ or +false+.
857
-
858
- <ruby>
859
- Client.exists?(1)
860
- </ruby>
861
-
862
- The +exists?+ method also takes multiple ids, but the catch is that it will return true if any one of those records exists.
863
-
864
- <ruby>
865
- Client.exists?(1,2,3)
866
- # or
867
- Client.exists?([1,2,3])
868
- </ruby>
869
-
870
- Further more, +exists+ takes a +conditions+ option much like find:
871
-
872
- <ruby>
873
- Client.exists?(:conditions => "first_name = 'Ryan'")
874
- </ruby>
875
-
876
- It's even possible to use +exists?+ without any arguments:
877
-
878
- <ruby>
879
- Client.exists?
880
- </ruby>
881
-
882
- The above returns +false+ if the +clients+ table is empty and +true+ otherwise.
883
-
884
- h3. Calculations
885
-
886
- This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
887
-
888
- <tt>count</tt> takes conditions much in the same way +exists?+ does:
889
-
890
- <ruby>
891
- Client.count(:conditions => "first_name = 'Ryan'")
892
- </ruby>
893
-
894
- Which will execute:
895
-
896
- <sql>
897
- SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
898
- </sql>
899
-
900
- You can also use +:include+ or +:joins+ for this to do something a little more complex:
901
-
902
- <ruby>
903
- Client.count(:conditions => "clients.first_name = 'Ryan' AND orders.status = 'received'", :include => "orders")
904
- </ruby>
905
-
906
- Which will execute:
907
-
908
- <sql>
909
- SELECT count(DISTINCT clients.id) AS count_all FROM clients
910
- LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
911
- (clients.first_name = 'Ryan' AND orders.status = 'received')
912
- </sql>
913
-
914
- This code specifies +clients.first_name+ just in case one of the join tables has a field also called +first_name+ and it uses +orders.status+ because that's the name of our join table.
915
-
916
- h4. Count
917
-
918
- 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)+.
919
-
920
- For options, please see the parent section, "Calculations":#calculations.
921
-
922
- h4. Average
923
-
924
- 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:
925
-
926
- <ruby>
927
- Client.average("orders_count")
928
- </ruby>
929
-
930
- This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
931
-
932
- For options, please see the parent section, "Calculations":#calculations.
933
-
934
- h4. Minimum
935
-
936
- 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:
937
-
938
- <ruby>
939
- Client.minimum("age")
940
- </ruby>
941
-
942
- For options, please see the parent section, "Calculations":#calculations.
943
-
944
- h4. Maximum
945
-
946
- 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:
947
-
948
- <ruby>
949
- Client.maximum("age")
950
- </ruby>
951
-
952
- For options, please see the parent section, "Calculations":#calculations.
953
-
954
- h4. Sum
955
-
956
- 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:
957
-
958
- <ruby>
959
- Client.sum("orders_count")
960
- </ruby>
961
-
962
- For options, please see the parent section, "Calculations":#calculations.
963
-
964
- h3. Changelog
965
-
966
- "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16
967
-
968
- * February 7, 2009: Second version by "Pratik":credits.html#lifo
969
- * December 29 2008: Initial version by "Ryan Bigg":credits.html#radar