Froze rails gems
[depot.git] / vendor / rails / railties / doc / guides / source / finders.txt
1 Rails Finders
2 =============
3
4 This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as other ways of finding particular instances of your models. By using this guide, you will be able to:
5
6 * Find records using a variety of methods and conditions
7 * Specify the order, retrieved attributes, grouping, and other properties of the found records
8 * Use eager loading to cut down on the number of database queries in your application
9 * Use dynamic finders
10 * Create named scopes to add custom finding behavior to your models
11 * Check for the existence of particular records
12 * Perform aggregate calculations on Active Record models
13
14 If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
15
16 == The Sample Models
17
18 This guide demonstrates finding using the following models:
19
20 [source,ruby]
21 -------------------------------------------------------
22 class Client < ActiveRecord::Base
23 has_one :address
24 has_one :mailing_address
25 has_many :orders
26 has_and_belongs_to_many :roles
27 end
28
29 class Address < ActiveRecord::Base
30 belongs_to :client
31 end
32
33 class MailingAddress < Address
34 end
35
36 class Order < ActiveRecord::Base
37 belongs_to :client, :counter_cache => true
38 end
39
40 class Role < ActiveRecord::Base
41 has_and_belongs_to_many :clients
42 end
43 -------------------------------------------------------
44
45 == Database Agnostic
46
47 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.
48
49 == IDs, First, Last and All
50
51 +ActiveRecord::Base+ has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is +find+. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type +Client.find(1)+ which would execute this query on your database:
52
53 [source, sql]
54 -------------------------------------------------------
55 SELECT * FROM +clients+ WHERE (+clients+.+id+ = 1)
56 -------------------------------------------------------
57
58 NOTE: Because this is a standard table created from a migration in Rail, the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.
59
60 If you wanted to find clients with id 1 or 2, you call +Client.find([1,2])+ or +Client.find(1,2)+ and then this will be executed as:
61
62 [source, sql]
63 -------------------------------------------------------
64 SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2))
65 -------------------------------------------------------
66
67 -------------------------------------------------------
68 >> Client.find(1,2)
69 => [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
70 created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
71 #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
72 created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
73 -------------------------------------------------------
74
75 Note that if you pass in a list of numbers that the result will be returned as an array, not as a single +Client+ object.
76
77 NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception.
78
79 If you wanted to find the first client you would simply type +Client.first+ and that would find the first client created in your clients table:
80
81 -------------------------------------------------------
82 >> Client.first
83 => #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
84 created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
85 -------------------------------------------------------
86
87 If you were running script/server you might see the following output:
88
89 [source,sql]
90 -------------------------------------------------------
91 SELECT * FROM clients LIMIT 1
92 -------------------------------------------------------
93
94 Indicating the query that Rails has performed on your database.
95
96 To find the last client you would simply type +Client.find(:last)+ and that would find the last client created in your clients table:
97
98 -------------------------------------------------------
99 >> Client.find(:last)
100 => #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
101 created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
102 -------------------------------------------------------
103
104 [source,sql]
105 -------------------------------------------------------
106 SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
107 -------------------------------------------------------
108
109 To find all the clients you would simply type +Client.all+ and that would find all the clients in your clients table:
110
111 -------------------------------------------------------
112 >> Client.all
113 => [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
114 created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
115 #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
116 created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
117 -------------------------------------------------------
118
119 As alternatives to calling +Client.first+, +Client.last+, and +Client.all+, you can use the class methods +Client.first+, +Client.last+, and +Client.all+ instead. +Client.first+, +Client.last+ and +Client.all+ just call their longer counterparts: +Client.find(:first)+, +Client.find(:last)+ and +Client.find(:all)+ respectively.
120
121 Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.find(:last)+ will both return a single object, where as +Client.all+/+Client.find(:all)+ will return an array of Client objects, just as passing in an array of ids to find will do also.
122
123 == Conditions
124
125 The +find+ method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.
126
127 === Pure String Conditions ===
128
129 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.
130
131 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.
132
133 === Array Conditions ===
134
135 Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. 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. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
136
137 The reason for doing code like:
138
139 [source, ruby]
140 -------------------------------------------------------
141 +Client.first(:conditions => ["orders_count = ?", params[:orders]])+
142 -------------------------------------------------------
143
144 instead of:
145
146 -------------------------------------------------------
147 +Client.first(:conditions => "orders_count = #{params[:orders]}")+
148 -------------------------------------------------------
149
150 is because of parameter 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 parameters directly inside the conditions string.
151
152 TIP: For more information on the dangers of SQL injection, see the link:../security.html#_sql_injection[Ruby on Rails Security Guide].
153
154 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:
155
156 [source, ruby]
157 -------------------------------------------------------
158 Client.all(:conditions => ["created_at IN (?)",
159 (params[:start_date].to_date)..(params[:end_date].to_date)])
160 -------------------------------------------------------
161
162 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.
163
164 [source, sql]
165 -------------------------------------------------------
166 SELECT * FROM +users+ WHERE (created_at IN
167 ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05',
168 '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11',
169 '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17',
170 '2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
171 ‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20',
172 '2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26',
173 '2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
174 -------------------------------------------------------
175
176 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:
177
178 [source, ruby]
179 -------------------------------------------------------
180 Client.all(:conditions => ["created_at IN (?)",
181 (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
182 -------------------------------------------------------
183
184 [source, sql]
185 -------------------------------------------------------
186 SELECT * FROM +users+ WHERE (created_at IN
187 ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ...
188 '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
189 -------------------------------------------------------
190
191 This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
192
193 -------------------------------------------------------
194 Got a packet bigger than 'max_allowed_packet' bytes: _query_
195 -------------------------------------------------------
196
197 Where _query_ is the actual query used to get that error.
198
199 In this example it would be better to use greater-than and less-than operators in SQL, like so:
200
201 [source, ruby]
202 -------------------------------------------------------
203 Client.all(:conditions =>
204 ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
205 -------------------------------------------------------
206
207 You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:
208
209 [source, ruby]
210 -------------------------------------------------------
211 Client.all(:conditions =>
212 ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
213 -------------------------------------------------------
214
215 Just like in Ruby.
216
217 === Hash Conditions ===
218
219 Similar to the array style of params you can also specify keys in your conditions:
220
221 [source, ruby]
222 -------------------------------------------------------
223 Client.all(:conditions =>
224 ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])
225 -------------------------------------------------------
226
227 This makes for clearer readability if you have a large number of variable conditions.
228
229 == Ordering
230
231 If you're getting a set of records and want to force an order, you can use +Client.all(:order => "created_at")+ which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using +Client.all(:order => "created_at desc")+
232
233 == Selecting Certain Fields
234
235 To select certain fields, you can use the select option like this: +Client.first(:select => "viewable_by, locked")+. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute +SELECT viewable_by, locked FROM clients LIMIT 0,1+ on your database.
236
237 == Limit & Offset
238
239 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. Take this code for example:
240
241 [source, ruby]
242 -------------------------------------------------------
243 Client.all(:limit => 5)
244 -------------------------------------------------------
245
246 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:
247
248 [source,sql]
249 -------------------------------------------------------
250 SELECT * FROM clients LIMIT 5
251 -------------------------------------------------------
252
253 [source, ruby]
254 -------------------------------------------------------
255 Client.all(:limit => 5, :offset => 5)
256 -------------------------------------------------------
257
258 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:
259
260 [source,sql]
261 -------------------------------------------------------
262 SELECT * FROM clients LIMIT 5, 5
263 -------------------------------------------------------
264
265 == Group
266
267 The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. You could use the option in this context:
268
269 [source, ruby]
270 -------------------------------------------------------
271 Order.all(:group => "date(created_at)", :order => "created_at")
272 -------------------------------------------------------
273
274 And this will give you a single +Order+ object for each date where there are orders in the database.
275
276 The SQL that would be executed would be something like this:
277
278 [source, sql]
279 -------------------------------------------------------
280 SELECT * FROM +orders+ GROUP BY date(created_at)
281 -------------------------------------------------------
282
283 == Read Only
284
285 Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an +Active Record::ReadOnlyRecord+ exception. To set this option, specify it like this:
286
287 [source, ruby]
288 -------------------------------------------------------
289 Client.first(:readonly => true)
290 -------------------------------------------------------
291
292 If you assign this record to a variable +client+, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
293
294 [source, ruby]
295 -------------------------------------------------------
296 client = Client.first(:readonly => true)
297 client.locked = false
298 client.save
299 -------------------------------------------------------
300
301 == Lock
302
303 If you're wanting to stop race conditions for a specific record (for example, you're incrementing a single field for a record, potentially from multiple simultaneous connections) you can use the lock option to ensure that the record is updated correctly. For safety, you should use this inside a transaction.
304
305 [source, ruby]
306 -------------------------------------------------------
307 Topic.transaction do
308 t = Topic.find(params[:id], :lock => true)
309 t.increment!(:views)
310 end
311 -------------------------------------------------------
312
313 == Making It All Work Together
314
315 You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement Active Record will use the latter.
316
317 == Eager Loading
318
319 Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use +Client.all(:include => :address)+. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include => [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:
320
321 [source, sql]
322 -------------------------------------------------------
323 Client Load (0.000383) SELECT * FROM clients
324 Address Load (0.119770) SELECT addresses.* FROM addresses
325 WHERE (addresses.client_id IN (13,14))
326 MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM
327 mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
328 -------------------------------------------------------
329
330 The numbers +13+ and +14+ in the above SQL are the ids of the clients gathered from the +Client.all+ query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called +address+ or +mailing_address+ on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.
331
332 If you wanted to get all the addresses for a client in the same query you would do +Client.all(:joins => :address)+ and you wanted to find the address and mailing address for that client you would do +Client.all(:joins => [:address, :mailing_address])+. This is more efficient because it does all the SQL in one query, as shown by this example:
333
334 [source, sql]
335 -------------------------------------------------------
336 +Client Load (0.000455) SELECT clients.* FROM clients INNER JOIN addresses
337 ON addresses.client_id = client.id INNER JOIN mailing_addresses ON
338 mailing_addresses.client_id = client.id
339 -------------------------------------------------------
340
341 This query is more efficent, but there's a gotcha: if you have a client who does not have an address or a mailing address they will not be returned in this query at all. If you have any association as an optional association, you may want to use include rather than joins. Alternatively, you can use a SQL join clause to specify exactly the join you need (Rails always assumes an inner join):
342
343 [source, ruby]
344 -------------------------------------------------------
345 Client.all(:joins => “LEFT OUTER JOIN addresses ON
346 client.id = addresses.client_id LEFT OUTER JOIN mailing_addresses ON
347 client.id = mailing_addresses.client_id”)
348 -------------------------------------------------------
349
350 When using eager loading you can specify conditions for the columns of the tables inside the eager loading to get back a smaller subset. If, for example, you want to find a client and all their orders within the last two weeks you could use eager loading with conditions for this:
351
352 [source, ruby]
353 -------------------------------------------------------
354 Client.first(:include => "orders", :conditions =>
355 ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
356 -------------------------------------------------------
357
358 == Dynamic finders
359
360 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+. 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)+. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type +find_by_name(params[:name])+ than it is to type +first(:conditions => ["name = ?", params[:name]])+.
361
362 There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. 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')+:
363
364 [source,sql]
365 -------------------------------------------------------
366 SELECT * FROM +clients+ WHERE (+clients+.+name+ = 'Ryan') LIMIT 1
367 BEGIN
368 INSERT INTO +clients+ (+name+, +updated_at+, +created_at+, +orders_count+, +locked+)
369 VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0')
370 COMMIT
371 -------------------------------------------------------
372
373 +find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will call +new+ with the parameters you passed in. For example:
374
375 [source, ruby]
376 -------------------------------------------------------
377 client = Client.find_or_initialize_by_name('Ryan')
378 -------------------------------------------------------
379
380 will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize 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.
381
382 == Finding By SQL
383
384 If you'd like to use your own SQL to find records a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:
385
386 [source, ruby]
387 -------------------------------------------------------
388 Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
389 -------------------------------------------------------
390
391 +find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
392
393 == +select_all+ ==
394
395 +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.
396
397 [source, ruby]
398 -------------------------------------------------------
399 Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
400 -------------------------------------------------------
401
402 == Working with Associations
403
404 When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like +Client.find(params[:id]).orders.find_by_sent_and_received(true, false)+. Having this find method available on associations is extremely helpful when using nested controllers.
405
406 == Named Scopes
407
408 Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.
409
410 === Simple Named Scopes
411
412 Suppose want to find all clients who are male. You could use this code:
413
414 [source, ruby]
415 -------------------------------------------------------
416 class Client < ActiveRecord::Base
417 named_scope :males, :conditions => { :gender => "male" }
418 end
419 -------------------------------------------------------
420
421 Then you could call +Client.males.all+ to get all the clients who are male. Please note that if you do not specify the +all+ on the end you will get a +Scope+ object back, not a set of records which you do get back if you put the +all+ on the end.
422
423 If you wanted to find all the clients who are active, you could use this:
424
425 [source,ruby]
426 -------------------------------------------------------
427 class Client < ActiveRecord::Base
428 named_scope :active, :conditions => { :active => true }
429 end
430 -------------------------------------------------------
431
432 You can call this new named_scope with +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do +Client.active.first+.
433
434 === Combining Named Scopes
435
436 If you wanted to find all the clients who are active and male you can stack the named scopes like this:
437
438 [source, ruby]
439 -------------------------------------------------------
440 Client.males.active.all
441 -------------------------------------------------------
442
443 If you would then like to do a +all+ on that scope, you can. Just like an association, named scopes allow you to call +all+ on them:
444
445 [source, ruby]
446 -------------------------------------------------------
447 Client.males.active.all(:conditions => ["age > ?", params[:age]])
448 -------------------------------------------------------
449
450 === Runtime Evaluation of Named Scope Conditions
451
452 Consider the following code:
453
454 [source, ruby]
455 -------------------------------------------------------
456 class Client < ActiveRecord::Base
457 named_scope :recent, :conditions => { :created_at > 2.weeks.ago }
458 end
459 -------------------------------------------------------
460
461 This looks like a standard named scope that defines a method called recent which gathers all records created any time between now and 2 weeks ago. That's correct for the first time the model is loaded but for any time after that, +2.weeks.ago+ is set to that same value, so you will consistently get records from a certain date until your model is reloaded by something like your application restarting. The way to fix this is to put the code in a lambda block:
462
463 [source, ruby]
464 -------------------------------------------------------
465 class Client < ActiveRecord::Base
466 named_scope :recent, lambda { { :conditions => ["created_at > ?", 2.weeks.ago] } }
467 end
468 -------------------------------------------------------
469
470 And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.
471
472 === Named Scopes with Multiple Models
473
474 In a named scope you can use +:include+ and +:joins+ options just like in find.
475
476 [source, ruby]
477 -------------------------------------------------------
478 class Client < ActiveRecord::Base
479 named_scope :active_within_2_weeks, :joins => :order,
480 lambda { { :conditions => ["orders.created_at > ?", 2.weeks.ago] } }
481 end
482 -------------------------------------------------------
483
484 This method, called as +Client.active_within_2_weeks.all+, will return all clients who have placed orders in the past 2 weeks.
485
486 === Arguments to Named Scopes
487
488 If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:
489
490 [source, ruby]
491 -------------------------------------------------------
492 class Client < ActiveRecord::Base
493 named_scope :recent, lambda { |time| { :conditions => ["created_at > ?", time] } }
494 end
495 -------------------------------------------------------
496
497 This will work if you call +Client.recent(2.weeks.ago).all+ but not if you call +Client.recent+. If you want to add an optional argument for this, you have to use the splat operator as the block's parameter.
498
499 [source, ruby]
500 -------------------------------------------------------
501 class Client < ActiveRecord::Base
502 named_scope :recent, lambda { |*args| { :conditions => ["created_at > ?", args.first || 2.weeks.ago] } }
503 end
504 -------------------------------------------------------
505
506 This will work with +Client.recent(2.weeks.ago).all+ and +Client.recent.all+, with the latter always returning records with a created_at date between right now and 2 weeks ago.
507
508 Remember that named scopes are stackable, so you will be able to do +Client.recent(2.weeks.ago).unlocked.all+ to find all clients created between right now and 2 weeks ago and have their locked field set to false.
509
510 === Anonymous Scopes
511
512 All Active Record models come with a named scope named +scoped+, which allows you to create anonymous scopes. For example:
513
514 [source, ruby]
515 -------------------------------------------------------
516 class Client < ActiveRecord::Base
517 def self.recent
518 scoped :conditions => ["created_at > ?", 2.weeks.ago]
519 end
520 end
521 -------------------------------------------------------
522
523 Anonymous scopes are most useful to create scopes "on the fly":
524
525 [source, ruby]
526 -------------------------------------------------------
527 Client.scoped(:conditions => { :gender => "male" })
528 -------------------------------------------------------
529
530 Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.
531
532 == Existence of Objects
533
534 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.
535
536 [source, ruby]
537 -------------------------------------------------------
538 Client.exists?(1)
539 -------------------------------------------------------
540
541 The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.
542
543 [source, ruby]
544 -------------------------------------------------------
545 Client.exists?(1,2,3)
546 # or
547 Client.exists?([1,2,3])
548 -------------------------------------------------------
549
550 The +exists?+ method also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.
551
552 Further more, +exists+ takes a +conditions+ option much like find:
553
554 [source, ruby]
555 -------------------------------------------------------
556 Client.exists?(:conditions => "first_name = 'Ryan'")
557 -------------------------------------------------------
558
559 == Calculations
560
561 This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
562
563 +count+ takes conditions much in the same way +exists?+ does:
564
565 [source, ruby]
566 -------------------------------------------------------
567 Client.count(:conditions => "first_name = 'Ryan'")
568 -------------------------------------------------------
569
570 Which will execute:
571
572 [source, sql]
573 -------------------------------------------------------
574 SELECT count(*) AS count_all FROM +clients+ WHERE (first_name = 1)
575 -------------------------------------------------------
576
577 You can also use +include+ or +joins+ for this to do something a little more complex:
578
579 [source, ruby]
580 -------------------------------------------------------
581 Client.count(:conditions => "clients.first_name = 'Ryan' AND orders.status = 'received'", :include => "orders")
582 -------------------------------------------------------
583
584 Which will execute:
585
586 [source, sql]
587 -------------------------------------------------------
588 SELECT count(DISTINCT +clients+.id) AS count_all FROM +clients+
589 LEFT OUTER JOIN +orders+ ON orders.client_id = client.id WHERE
590 (clients.first_name = 'name' AND orders.status = 'received')
591 -------------------------------------------------------
592
593 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.
594
595
596 === Count
597
598 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)+.
599
600 For options, please see the parent section, Calculations.
601
602 === Average
603
604 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:
605
606 [source, ruby]
607 -------------------------------------------------------
608 Client.average("orders_count")
609 -------------------------------------------------------
610
611 This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
612
613 For options, please see the parent section, <<_calculations, Calculations>>
614
615 === Minimum
616
617 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:
618
619 [source, ruby]
620 -------------------------------------------------------
621 Client.minimum("age")
622 -------------------------------------------------------
623
624 For options, please see the parent section, <<_calculations, Calculations>>
625
626 === Maximum
627
628 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:
629
630 [source, ruby]
631 -------------------------------------------------------
632 Client.maximum("age")
633 -------------------------------------------------------
634
635 For options, please see the parent section, <<_calculations, Calculations>>
636
637 === Sum
638
639 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:
640
641 [source, ruby]
642 -------------------------------------------------------
643 Client.sum("orders_count")
644 -------------------------------------------------------
645
646 For options, please see the parent section, <<_calculations, Calculations>>
647
648 == Credits
649
650 Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.
651
652 Thanks to Mike Gunderloy for his tips on creating this guide.
653
654 == Changelog
655
656 http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket]
657
658 * November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
659 * October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg
660 * October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg
661 * October 26, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
662 * October 22, 2008: Calculations complete, first complete draft by Ryan Bigg
663 * October 21, 2008: Extended named scope section by Ryan Bigg
664 * October 9, 2008: Lock, count, cleanup by Ryan Bigg
665 * October 6, 2008: Eager loading by Ryan Bigg
666 * October 5, 2008: Covered conditions by Ryan Bigg
667 * October 1, 2008: Covered limit/offset, formatting changes by Ryan Bigg
668 * September 28, 2008: Covered first/last/all by Ryan Bigg