aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source/active_record_querying.textile
diff options
context:
space:
mode:
authorPratik Naik <pratiknaik@gmail.com>2009-02-24 12:29:25 +0000
committerPratik Naik <pratiknaik@gmail.com>2009-02-24 12:29:25 +0000
commit53cd102b39eb62567298430cbd94e40dd78d46a0 (patch)
tree3d8a087421f0d74da7a7c3878e3ad1dddbf23697 /railties/guides/source/active_record_querying.textile
parente56b3e4c0b60b2b86f5ca9c5e5a0b22fa34d37ab (diff)
downloadrails-53cd102b39eb62567298430cbd94e40dd78d46a0.tar.gz
rails-53cd102b39eb62567298430cbd94e40dd78d46a0.tar.bz2
rails-53cd102b39eb62567298430cbd94e40dd78d46a0.zip
Merge with docrails
Diffstat (limited to 'railties/guides/source/active_record_querying.textile')
-rw-r--r--railties/guides/source/active_record_querying.textile631
1 files changed, 414 insertions, 217 deletions
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile
index ffffecace3..5da15bbb5c 100644
--- a/railties/guides/source/active_record_querying.textile
+++ b/railties/guides/source/active_record_querying.textile
@@ -16,6 +16,10 @@ If you're used to using raw SQL to find database records then, generally, you wi
Code examples throughout this guide will refer to one or more of the following models:
+TIP: All of the following models uses +id+ as the primary key, unless specified otherwise.
+
+<br />
+
<ruby>
class Client < ActiveRecord::Base
has_one :address
@@ -48,99 +52,147 @@ class Role < ActiveRecord::Base
end
</ruby>
-bq. 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.
+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.
-h3. Retrieving objects
+h3. Retrieving objects from the database
-To retrieve objects from the database, Active Record provides a primary method called +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:
+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.
-<sql>
-SELECT * FROM clients WHERE (clients.id = 1)
-</sql>
+Primary operation of <tt>Model.find(options)</tt> can be summarized as:
-NOTE: Because this is a standard table created from a migration in Rails, 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.
+* Convert the supplied options to an equivalent SQL query.
+* Fire the SQL query and retrieve the corresponding results from the database.
+* Instantiate the equivalent Ruby object of the appropriate model for every resulting row.
+* Run +after_find+ callbacks if any.
-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:
+h4. Retrieving a single object
+
+Active Record lets you retrieve a single object using three different ways.
+
+h5. Using a primary key
+
+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:
+
+<ruby>
+# Find the client with primary key (id) 10.
+client = Client.find(10)
+=> #<Client id: 10, name: => "Ryan">
+</ruby>
+
+SQL equivalent of the above is:
<sql>
-SELECT * FROM clients WHERE (clients.id IN (1,2))
+SELECT * FROM clients WHERE (clients.id = 10)
</sql>
-<shell>
->> Client.find(1,2)
-=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
- created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
- #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
-</shell>
-
-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.
+<tt>Model.find(primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception if no matching record is found.
-NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a RecordNotFound exception.
+h5. Find first
-If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client in your clients table:
+<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:
-<shell>
->> Client.first
-=> #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
- created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
-</shell>
+<ruby>
+client = Client.first
+=> #<Client id: 1, name: => "Lifo">
+</ruby>
-If you were reading your log file (the default is log/development.log) you may see something like this:
+SQL equivalent of the above is:
<sql>
SELECT * FROM clients LIMIT 1
</sql>
-Indicating the query that Rails has performed on your database.
+<tt>Model.first</tt> returns +nil+ if no matching record is found. No exception will be raised.
-To find the last Client object you would simply type +Client.last+ and that would find the last client created in your clients table:
+NOTE: +Model.find(:first, options)+ is equivalent to +Model.first(options)+
-<shell>
->> Client.last
-=> #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
-</shell>
+h5. Find last
+
+<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:
-If you were reading your log file (the default is log/development.log) you may see something like this:
+<ruby>
+# Find the client with primary key (id) 10.
+client = Client.last
+=> #<Client id: 221, name: => "Russel">
+</ruby>
+
+SQL equivalent of the above is:
<sql>
-SELECT * FROM clients ORDER BY id DESC LIMIT 1
+SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
</sql>
-NOTE: Please be aware that the syntax that Rails uses to find the first record in the table means that it may not be the actual first record. If you want the actual first record based on a field in your table (e.g. +created_at+) specify an order option in your find call. The last method call works differently: it finds the last record on your table based on the primary key column.
+<tt>Model.last</tt> returns +nil+ if no matching record is found. No exception will be raised.
+
+NOTE: +Model.find(:last, options)+ is equivalent to +Model.last(options)+
+
+h4. Retrieving multiple objects
+
+h5. Using multiple primary keys
+
+<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:
+
+<ruby>
+# Find the clients with primary keys 1 and 10.
+client = Client.find(1, 10) # Or even Client.find([1, 10])
+=> [#<Client id: 1, name: => "Lifo">, #<Client id: 10, name: => "Ryan">]
+</ruby>
+
+SQL equivalent of the above is:
<sql>
-SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
+SELECT * FROM clients WHERE (clients.id IN (1,10))
</sql>
-To find all the Client objects you would simply type +Client.all+ and that would find all the clients in your clients table:
+<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.
-<shell>
->> Client.all
-=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
- created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
- #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
-</shell>
+h5. Find all
-You may see in Rails code that there are calls to methods such as +Client.find(:all)+, +Client.find(:first)+ and +Client.find(:last)+. These methods are just alternatives to +Client.all+, +Client.first+ and +Client.last+ respectively.
+<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.
-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.
+<ruby>
+# Find all the clients.
+clients = Client.all
+=> [#<Client id: 1, name: => "Lifo">, #<Client id: 10, name: => "Ryan">, #<Client id: 221, name: => "Russel">]
+</ruby>
+
+And the equivalent SQL is:
+
+<sql>
+SELECT * FROM clients
+</sql>
+
+<tt>Model.all</tt> returns an empty array +[]+ if no matching record is found. No exception will be raised.
+
+NOTE: +Model.find(:all, options)+ is equivalent to +Model.all(options)+
h3. Conditions
-The +find+ method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.
+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.
-h4. Pure String Conditions
+h4. Pure string conditions
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.
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.
-h4. Array Conditions
+h4. Array conditions
+
+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:
-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 +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 the SQL representation of +false+, which depends on the adapter.
+<ruby>
+Client.first(:conditions => ["orders_count = ?", params[:orders]])
+</ruby>
+
+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.
+
+Or if you want to specify two conditions, you can do it like:
+
+<ruby>
+Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])
+</ruby>
+
+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.
The reason for doing code like:
@@ -158,7 +210,20 @@ is because of argument safety. Putting the variable directly into the conditions
TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":../security.html#_sql_injection.
-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:
+h5. Placeholder conditions
+
+Similar to the +(?)+ replacement style of params, you can also specify keys/values hash in your Array conditions:
+
+<ruby>
+Client.all(:conditions =>
+ ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])
+</ruby>
+
+This makes for clearer readability if you have a large number of variable conditions.
+
+h5. Range conditions
+
+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:
<ruby>
Client.all(:conditions => ["created_at IN (?)",
@@ -178,6 +243,8 @@ SELECT * FROM users WHERE (created_at IN
'2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
</sql>
+h5. Time and Date conditions
+
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:
<ruby>
@@ -215,20 +282,13 @@ Client.all(:conditions =>
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.
-h4. Placeholder Conditions
+h4. Hash conditions
-Similar to the array style of params you can also specify keys in your conditions:
+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:
-<ruby>
-Client.all(:conditions =>
- ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])
-</ruby>
-
-This makes for clearer readability if you have a large number of variable conditions.
-
-h4. Hash Conditions
+NOTE: Only equality, range and subset checking are possible with Hash conditions.
-Rails 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:
+h5. Equality conditions
<ruby>
Client.all(:conditions => { :locked => true })
@@ -240,13 +300,15 @@ The field name does not have to be a symbol it can also be a string:
Client.all(:conditions => { 'locked' => true })
</ruby>
+h5. Range conditions
+
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.
<ruby>
Client.all(:conditions => { :created_at => (Time.now.midnight - 1.day)..Time.now.midnight})
</ruby>
-This will find all clients created yesterday by using a BETWEEN sql statement:
+This will find all clients created yesterday by using a +BETWEEN+ SQL statement:
<sql>
SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
@@ -254,39 +316,81 @@ SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AN
This demonstrates a shorter syntax for the examples in "Array Conditions":#array-conditions
-You can also join in tables and specify their columns in the hash:
+h5. Subset conditions
+
+If you want to find records using the +IN+ expression you can pass an array to the conditions hash:
<ruby>
-Client.all(:include => "orders", :conditions => { 'orders.created_at' => (Time.now.midnight - 1.day)..Time.now.midnight })
+Client.all(:conditions => { :orders_count => [1,3,5] })
</ruby>
-An alternative and cleaner syntax to this is:
+This code will generate SQL like this:
+
+<sql>
+SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
+</sql>
+
+h3. Find options
+
+Apart from +:conditions+, +Model.find+ takes a variety of other options via the options hash for customizing the resulting record set.
<ruby>
-Client.all(:include => "orders", :conditions => { :orders => { :created_at => (Time.now.midnight - 1.day)..Time.now.midnight } })
+Model.find(id_or_array_of_ids, options_hash)
+Model.find(:last, options_hash)
+Model.find(:first, options_hash)
+
+Model.first(options_hash)
+Model.last(options_hash)
+Model.all(options_hash)
</ruby>
-This will find all clients who have orders that were created yesterday, again using a BETWEEN expression.
+The following sections give a top level overview of all the possible keys for the +options_hash+.
+
+h4. Ordering
+
+To retrieve records from the database in a specific order, you can specify the +:order+ option to the +find+ call.
-If you want to find records using the IN expression you can pass an array to the conditions hash:
+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:
<ruby>
-Client.all(:include => "orders", :conditions => { :orders_count => [1,3,5] }
+Client.all(:order => "created_at")
</ruby>
-This code will generate SQL like this:
+You could specify +ASC+ or +DESC+ as well:
-<sql>
-SELECT * FROM clients WHERE (clients.orders_count IN (1,2,3))
-</sql>
+<ruby>
+Client.all(:order => "created_at DESC")
+# OR
+Client.all(:order => "created_at ASC")
+</ruby>
+
+Or ordering by multiple fields:
+
+<ruby>
+Client.all(:order => "orders_count ASC, created_at DESC")
+</ruby>
+
+h4. Selecting specific fields
+
+By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
-h3. Ordering
+To select only a subset of fields from the result set, you can specify the subset via +:select+ option on the +find+.
-If you're getting a set of records and want to order them in ascending order by the +created_at+ field in your table, you can use +Client.all(:order => "created_at")+. If you'd like to order it in descending order, just tell it to do that using +Client.all(:order => "created_at desc")+. The value for this option is passed in as sanitized SQL and allows you to sort via multiple fields: +Client.all(:order => "created_at desc, orders_count asc")+.
+NOTE: If the +:select+ option is used, all the returning objects will be "read only":#read-only objects.
-h3. Selecting Certain Fields
+<br />
+
+For example, to select only +viewable_by+ and +locked+ columns:
+
+<ruby>
+Client.all(:select => "viewable_by, locked")
+</ruby>
-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 1+ on your database.
+The SQL query used by this find call will be somewhat like:
+
+<sql>
+SELECT viewable_by, locked FROM clients
+</sql>
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:
@@ -294,13 +398,19 @@ Be careful because this also means you're initializing a model object with only
ActiveRecord::MissingAttributeError: missing attribute: <attribute>
</shell>
-Where <attribute> is the atrribute 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.
+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.
+
+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:
+
+<ruby>
+Client.all(:select => "DISTINCT(name)")
+</ruby>
-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: +Client.all(:select => "DISTINCT(name)")+.
+h4. Limit and Offset
-h3. Limit & Offset
+To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +:limit+ and +:offset+ options on the find.
-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:
+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:
<ruby>
Client.all(:limit => 5)
@@ -312,6 +422,8 @@ This code will return a maximum of 5 clients and because it specifies no offset
SELECT * FROM clients LIMIT 5
</sql>
+Or specifying both +:limit+ and +:offset+:
+
<ruby>
Client.all(:limit => 5, :offset => 5)
</ruby>
@@ -322,9 +434,11 @@ This code will return a maximum of 5 clients and because it specifies an offset
SELECT * FROM clients LIMIT 5, 5
</sql>
-h3. Group
+h4. Group
+
+To apply +GROUP BY+ clause to the SQL fired by the +Model.find+, you can specify the +:group+ option on the find.
-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:
+For example, if you want to find a collection of the dates orders were created on:
<ruby>
Order.all(:group => "date(created_at)", :order => "created_at")
@@ -338,27 +452,35 @@ The SQL that would be executed would be something like this:
SELECT * FROM orders GROUP BY date(created_at)
</sql>
-h3. Having
+h4. Having
-The +:having+ option allows you to specify SQL and acts as a kind of a filter on the group option. +:having+ can only be specified when +:group+ is specified.
+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.
-An example of using it would be:
+For example:
<ruby>
Order.all(:group => "date(created_at)", :having => ["created_at > ?", 1.month.ago])
</ruby>
+The SQL that would be executed would be something like this:
+
+<sql>
+SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15'
+</sql>
+
This will return single order objects for each day, but only for the last month.
-h3. Read Only
+h4. Readonly objects
+
+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.
-+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 ActiveRecord::ReadOnlyRecord exception. To set this option, specify it like this:
+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:
<ruby>
Client.first(:readonly => true)
</ruby>
-If you assign this record to a variable client, calling the following code will raise an ActiveRecord::ReadOnlyRecord exception:
+If you assign this record to a variable client, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
<ruby>
client = Client.first(:readonly => true)
@@ -366,238 +488,304 @@ client.locked = false
client.save
</ruby>
-h3. Lock
+h4. Locking records for update
-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.
+Locking is helpful for preventing the race conditions when updating records in the database and ensuring atomic updated. Active Record provides two locking mechanism:
+
+* Optimistic Locking
+* Pessimistic Locking
+
+h5. Optimistic Locking
+
+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.
+
+<strong>Optimistic locking column</strong>
+
+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:
<ruby>
-Topic.transaction do
- t = Topic.find(params[:id], :lock => true)
- t.increment!(:views)
-end
+c1 = Client.find(1)
+c2 = Client.find(1)
+
+c1.name = "Michael"
+c1.save
+
+c2.name = "should fail"
+c2.save # Raises a ActiveRecord::StaleObjectError
</ruby>
-You can also pass SQL to this 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:
+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.
+
+NOTE: You must ensure that your database schema defaults the +lock_version+ column to +0+.
+
+<br />
+
+This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
+
+To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class method called +set_locking_column+:
<ruby>
-Topic.transaction do
- t = Topic.find(params[:id], :lock => "LOCK IN SHARE MODE")
- t.increment!(:views)
+class Client < ActiveRecord::Base
+ set_locking_column :lock_client_column
end
</ruby>
-h3. Making It All Work Together
+h5. Pessimistic Locking
-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+ method Active Record will use the last one you specified. This is because the options passed to find are a hash and defining the same key twice in a hash will result in the last definition being used.
+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.
-h3. Eager Loading
+For example:
-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:
+<ruby>
+Item.transaction do
+ i = Item.first(:lock => true)
+ i.name = 'Jones'
+ i.save
+end
+</ruby>
+
+The above session produces the following SQL for a MySQL backend:
<sql>
-Client Load (0.000383) SELECT * FROM clients
-Address Load (0.119770) SELECT addresses.* FROM addresses
- WHERE (addresses.client_id IN (13,14))
-MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM
- mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
+SQL (0.2ms) BEGIN
+Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
+Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
+SQL (0.8ms) COMMIT
</sql>
-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 and is often called the "N+1 query problem". The problem is that the more queries your server has to execute, the slower it will run.
+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:
-If you wanted to get all the addresses for a client in the same query you would do +Client.all(:joins => :address)+.
-If 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:
+<ruby>
+Item.transaction do
+ i = Item.find(1, :lock => "LOCK IN SHARE MODE")
+ i.increment!(:views)
+end
+</ruby>
-<sql>
-+Client Load (0.000455) SELECT clients.* FROM clients INNER JOIN addresses
- ON addresses.client_id = client.id INNER JOIN mailing_addresses ON
- mailing_addresses.client_id = client.id
-</sql>
+h3. Joining tables
-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):
+<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:
+
+h4. Using a string SQL fragment
+
+You can just supply the raw SQL specifying the +JOIN+ clause to the +:joins+ option. For example:
<ruby>
-Client.all(:joins => “LEFT OUTER JOIN addresses ON
- client.id = addresses.client_id LEFT OUTER JOIN mailing_addresses ON
- client.id = mailing_addresses.client_id”)
+Client.all(:joins => 'LEFT OUTER JOIN addresses ON addresses.client_id = client.id')
</ruby>
-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:
+This will result in the following SQL:
+
+<sql>
+SELECT clients.* FROM clients INNER JOIN addresses ON addresses.client_id = clients.id
+</sql>
+
+h4. Using Array/Hash of named associations
+
+WARNING: This method only works with +INNER JOIN+,
+
+<br />
+
+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.
+
+For example, consider the following +Category+, +Post+, +Comments+ and +Guest+ models:
<ruby>
-Client.first(:include => "orders", :conditions =>
- ["orders.created_at >= ? AND orders.created_at <= ?", 2.weeks.ago, Time.now])
-</ruby>
+class Category < ActiveRecord::Base
+ has_many :posts
+end
-h3. Dynamic finders
+class Post < ActiveRecord::Base
+ belongs_to :category
+ has_many :comments
+ has_many :tags
+end
-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+.
+class Comments < ActiveRecord::Base
+ belongs_to :post
+ has_one :guest
+end
-You can do +find_last_by_*+ methods too which will find the last record matching your argument.
+class Guest < ActiveRecord::Base
+ belongs_to :comment
+end
+</ruby>
-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")+
+Now all of the following will produce the expected join queries using +INNER JOIN+:
-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)+.
+h5. Joining a single association
+<ruby>
+Category.all :joins => :posts
+</ruby>
-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")+:
+This produces:
<sql>
-SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1
-BEGIN
-INSERT INTO clients (name, updated_at, created_at, orders_count, locked)
- VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', 0, '0')
-COMMIT
+SELECT categories.* FROM categories
+ INNER JOIN posts ON posts.category_id = categories.id
</sql>
-+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:
+h5. Joining multiple associations
<ruby>
-client = Client.find_or_initialize_by_name('Ryan')
+Post.all :joins => [:category, :comments]
</ruby>
-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.
-
+This produces:
-h3. Finding By SQL
+<sql>
+SELECT posts.* FROM posts
+ INNER JOIN categories ON posts.category_id = categories.id
+ INNER JOIN comments ON comments.post_id = posts.id
+</sql>
-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:
+h5. Joining nested associations (single level)
<ruby>
-Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
+Post.all :joins => {:comments => :guest}
</ruby>
-+find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
+h5. Joining nested associations (multiple level)
-h3. select_all
+<ruby>
+Category.all :joins => {:posts => [{:comments => :guest}, :tags]}
+</ruby>
+
+h4. Specifying conditions on the joined tables
-+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.
+You can specify conditions on the joined tables using the regular "Array":#arrayconditions and "String":#purestringconditions conditions. "Hash conditions":#hashconditions provides a special syntax for specifying conditions for the joined tables:
<ruby>
-Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
+time_range = (Time.now.midnight - 1.day)..Time.now.midnight
+Client.all :joins => :orders, :conditions => {'orders.created_at' => time_range}
</ruby>
-h3. Working with Associations
+An alternative and cleaner syntax to this is to nest the hash conditions:
+
+<ruby>
+time_range = (Time.now.midnight - 1.day)..Time.now.midnight
+Client.all :joins => :orders, :conditions => {:orders => {:created_at => time_range}}
+</ruby>
-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 resources.
+This will find all clients who have orders that were created yesterday, again using a +BETWEEN+ SQL expression.
-h3. Named Scopes
+h3. Eager loading associations
-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.
+Eager loading is the mechanism for loading the associated records of the objects returned by +Model.find+ using as few queries as possible.
-h4. Simple Named Scopes
+<strong>N <plus> 1 queries problem</strong>
-Suppose we want to find all clients who are male. You could use this code:
+Consider the following code, which finds 10 clients and prints their postcodes:
<ruby>
-class Client < ActiveRecord::Base
- named_scope :males, :conditions => { :gender => "male" }
+clients = Client.all(:limit => 10)
+
+clients.each do |client|
+ puts client.address.postcode
end
</ruby>
-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.
+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.
+
+<strong>Solution to N <plus> 1 queries problem</strong>
-If you wanted to find all the clients who are active, you could use this:
+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.
+
+Revisiting the above case, we could rewrite +Client.all+ to use eager load addresses:
<ruby>
-class Client < ActiveRecord::Base
- named_scope :active, :conditions => { :active => true }
+clients = Client.all(:include => :address, :limit => 10)
+
+clients.each do |client|
+ puts client.address.postcode
end
</ruby>
-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])+. If you want to find the first client within this named scope you could do +Client.active.first+.
+The above code will execute just <strong>2</strong> queries, as opposed to <strong>11</strong> queries in the previous case:
-h4. Combining Named Scopes
+<sql>
+SELECT * FROM clients
+SELECT addresses.* FROM addresses
+ WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
+</sql>
-If you wanted to find all the clients who are active and male you can stack the named scopes like this:
+h4. Eager loading multiple associations
-<ruby>
-Client.males.active.all
-</ruby>
+Active Record lets you eager load any possible number of associations with a single +Model.find+ call by using Array, Hash or a nested Hash of Array/Hash with +:include+ find option.
-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:
+h5. Array of multiple associations
<ruby>
-Client.males.active.all(:conditions => ["age > ?", params[:age]])
+Post.all :include => [:category, :comments]
</ruby>
-h4. Runtime Evaluation of Named Scope Conditions
+This loads all the posts and the associated category and comments for each post.
-Consider the following code:
+h5. Nested assocaitions hash
<ruby>
-class Client < ActiveRecord::Base
- named_scope :recent, :conditions => { :created_at > 2.weeks.ago }
-end
+Category.find 1, :include => {:posts => [{:comments => :guest}, :tags]}
</ruby>
-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:
+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.
-<ruby>
-class Client < ActiveRecord::Base
- named_scope :recent, lambda { { :conditions => ["created_at > ?", 2.weeks.ago] } }
-end
-</ruby>
+h4. Specifying conditions on eager loaded associations
-And now every time the +recent+ named scope is called, the code in the lambda block will be executed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.
+Even though Active Record lets you specify conditions on the eager loaded associations just like +:joins+, the recommended way is to use ":joins":#joiningtables instead.
-h4. Named Scopes with Multiple Models
+h3. Dynamic finders
-In a named scope you can use +:include+ and +:joins+ options just like in +find+.
+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+.
-<ruby>
-class Client < ActiveRecord::Base
- named_scope :active_within_2_weeks, :joins => :order,
- lambda { { :conditions => ["orders.created_at > ?", 2.weeks.ago] } }
-end
-</ruby>
+You can do +find_last_by_*+ methods too which will find the last record matching your argument.
-This method, called as +Client.active_within_2_weeks.all+, will return all clients who have placed orders in the past 2 weeks.
+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")+
-h4. Arguments to Named Scopes
+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)+.
-If you want to pass to a named scope a required arugment, just specify it as a block argument like this:
-<ruby>
-class Client < ActiveRecord::Base
- named_scope :recent, lambda { |time| { :conditions => ["created_at > ?", time] } }
-end
-</ruby>
+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")+:
-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 prefix the arugment with an *.
+<sql>
+SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1
+BEGIN
+INSERT INTO clients (name, updated_at, created_at, orders_count, locked)
+ VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', 0, '0')
+COMMIT
+</sql>
+
++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:
<ruby>
-class Client < ActiveRecord::Base
- named_scope :recent, lambda { |*args| { :conditions => ["created_at > ?", args.first || 2.weeks.ago] } }
-end
+client = Client.find_or_initialize_by_name('Ryan')
</ruby>
-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.
-
-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.
+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.
-h4. Anonymous Scopes
+h3. Finding By SQL
-All Active Record models come with a named scope named +scoped+, which allows you to create anonymous scopes. For example:
+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:
<ruby>
-class Client < ActiveRecord::Base
- def self.recent
- scoped :conditions => ["created_at > ?", 2.weeks.ago]
- end
-end
+Client.find_by_sql("SELECT * FROM clients
+ INNER JOIN orders ON clients.id = orders.client_id
+ ORDER clients.created_at desc")
</ruby>
-Anonymous scopes are most useful to create scopes "on the fly":
++find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
+
+h3. select_all
+
+<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.
<ruby>
-Client.scoped(:conditions => { :gender => "male" })
+Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
</ruby>
-Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.
-
h3. Existence of Objects
-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+.
+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+.
<ruby>
Client.exists?(1)
@@ -617,11 +805,19 @@ Further more, +exists+ takes a +conditions+ option much like find:
Client.exists?(:conditions => "first_name = 'Ryan'")
</ruby>
+It's even possible to use +exists?+ without any arguments:
+
+<ruby>
+Client.exists?
+</ruby>
+
+The above returns +false+ if the +clients+ table is empty and +true+ otherwise.
+
h3. Calculations
This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
-+count+ takes conditions much in the same way +exists?+ does:
+<tt>count</tt> takes conditions much in the same way +exists?+ does:
<ruby>
Client.count(:conditions => "first_name = 'Ryan'")
@@ -701,4 +897,5 @@ h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16
-* December 29 2008: Initial version by Ryan Bigg
+* February 7, 2009: Second version by "Pratik":credits.html#lifo
+* December 29 2008: Initial version by "Ryan Bigg":credits.html#radar