<divclass="para"><p>This guide covers the <tt>find</tt> method defined in <tt>ActiveRecord::Base</tt>, as well as other ways of finding particular instances of your models. By using this guide, you will be able to:</p></div>
<divclass="ilist"><ul>
<li>
<p>
Find records using a variety of methods and conditions
</p>
</li>
<li>
<p>
Specify the order, retrieved attributes, grouping, and other properties of the found records
</p>
</li>
<li>
<p>
Use eager loading to cut down on the number of database queries in your application
</p>
</li>
<li>
<p>
Use dynamic finders
</p>
</li>
<li>
<p>
Create named scopes to add custom finding behavior to your models
</p>
</li>
<li>
<p>
Check for the existence of particular records
</p>
</li>
<li>
<p>
Perform aggregate calculations on Active Record models
</p>
</li>
</ul></div>
<divclass="para"><p>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.</p></div>
<divclass="para"><p>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.</p></div>
<divclass="para"><p><tt>ActiveRecord::Base</tt> 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 <tt>find</tt>. 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 <tt>Client.find(1)</tt> which would execute this query on your database:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<tdclass="content">Because this is a standard table created from a migration in Rail, the primary key is defaulted to <em>id</em>. 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.</td>
<divclass="para"><p>If you wanted to find clients with id 1 or 2, you call <tt>Client.find([1,2])</tt> or <tt>Client.find(1,2)</tt> and then this will be executed as:</p></div>
<divclass="para"><p>Note that if you pass in a list of numbers that the result will be returned as an array, not as a single <tt>Client</tt> object.</p></div>
<divclass="admonitionblock">
<table><tr>
<tdclass="icon">
<imgsrc="./images/icons/note.png"alt="Note"/>
</td>
<tdclass="content">If <tt>find(id)</tt> or <tt>find([id1, id2])</tt> fails to find any records, it will raise a <tt>RecordNotFound</tt> exception.</td>
</tr></table>
</div>
<divclass="para"><p>If you wanted to find the first client you would simply type <tt>Client.first</tt> and that would find the first client created in your clients table:</p></div>
<divclass="para"><p>Indicating the query that Rails has performed on your database.</p></div>
<divclass="para"><p>To find the last client you would simply type <tt>Client.find(:last)</tt> and that would find the last client created in your clients table:</p></div>
<divclass="para"><p>To find all the clients you would simply type <tt>Client.all</tt> and that would find all the clients in your clients table:</p></div>
<divclass="para"><p>As alternatives to calling <tt>Client.first</tt>, <tt>Client.last</tt>, and <tt>Client.all</tt>, you can use the class methods <tt>Client.first</tt>, <tt>Client.last</tt>, and <tt>Client.all</tt> instead. <tt>Client.first</tt>, <tt>Client.last</tt> and <tt>Client.all</tt> just call their longer counterparts: <tt>Client.find(:first)</tt>, <tt>Client.find(:last)</tt> and <tt>Client.find(:all)</tt> respectively.</p></div>
<divclass="para"><p>Be aware that <tt>Client.first</tt>/<tt>Client.find(:first)</tt> and <tt>Client.last</tt>/<tt>Client.find(:last)</tt> will both return a single object, where as <tt>Client.all</tt>/<tt>Client.find(:all)</tt> will return an array of Client objects, just as passing in an array of ids to find will do also.</p></div>
<divclass="para"><p>The <tt>find</tt> method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.</p></div>
<h3id="_pure_string_conditions">4.1. Pure String Conditions</h3>
<divclass="para"><p>If you'd like to add conditions to your find, you could just specify them in there, just like <tt>Client.first(:conditions ⇒ "orders_count = <em>2</em>")</tt>. This will find all clients where the <tt>orders_count</tt> field's value is 2.</p></div>
<tdclass="content">Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, <tt>Client.first(:conditions ⇒ "name LIKE <em>%#{params[:name]}%</em>")</tt> is not safe. See the next section for the preferred way to handle conditions using an array.</td>
<divclass="para"><p>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 <tt>Client.first(:conditions ⇒ ["orders_count = ?", params[:orders]])</tt>. 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 <tt>Client.first(:conditions ⇒ ["orders_count = ? AND locked = ?", params[:orders], false])</tt>. 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 <em>2</em> as its value for the orders_count field and <em>false</em> for its locked field.</p></div>
<divclass="para"><p>is because of parameter safety. Putting the variable directly into the conditions string will pass the variable to the database <strong>as-is</strong>. 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.</p></div>
<divclass="admonitionblock">
<table><tr>
<tdclass="icon">
<imgsrc="./images/icons/tip.png"alt="Tip"/>
</td>
<tdclass="content">For more information on the dangers of SQL injection, see the <ahref="../security.html#_sql_injection">Ruby on Rails Security Guide</a>.</td>
</tr></table>
</div>
<divclass="para"><p>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:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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.</p></div>
<divclass="para"><p>Things can get <strong>really</strong> messy if you pass in time objects as it will attempt to compare your field to <strong>every second</strong> in that range:</p></div>
<divclass="para"><p>This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:</p></div>
<divclass="para"><p>If you're getting a set of records and want to force an order, you can use <tt>Client.all(:order ⇒ "created_at")</tt> 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 <tt>Client.all(:order ⇒ "created_at desc")</tt></p></div>
<divclass="para"><p>To select certain fields, you can use the select option like this: <tt>Client.first(:select ⇒ "viewable_by, locked")</tt>. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute <tt>SELECT viewable_by, locked FROM clients LIMIT 0,1</tt> on your database.</p></div>
<divclass="para"><p>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:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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 <tt>Active Record::ReadOnlyRecord</tt> exception. To set this option, specify it like this:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>If you assign this record to a variable <tt>client</tt>, calling the following code will raise an <tt>ActiveRecord::ReadOnlyRecord</tt> exception:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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.</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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.</p></div>
<divclass="para"><p>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 <tt>Client.all(:include ⇒ :address)</tt>. 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:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>The numbers <tt>13</tt> and <tt>14</tt> in the above SQL are the ids of the clients gathered from the <tt>Client.all</tt> 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 <tt>address</tt> or <tt>mailing_address</tt> 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.</p></div>
<divclass="para"><p>If you wanted to get all the addresses for a client in the same query you would do <tt>Client.all(:joins ⇒ :address)</tt> and you wanted to find the address and mailing address for that client you would do <tt>Client.all(:joins ⇒ [:address, :mailing_address])</tt>. This is more efficient because it does all the SQL in one query, as shown by this example:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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):</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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:</p></div>
<divclass="para"><p>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 <tt>name</tt> on your Client model for example, you get <tt>find_by_name</tt> and <tt>find_all_by_name</tt> for free from Active Record. If you have also have a <tt>locked</tt> field on the client model, you also get <tt>find_by_locked</tt> and <tt>find_all_by_locked</tt>. If you want to find both by name and locked, you can chain these finders together by simply typing <tt>and</tt> between the fields for example <tt>Client.find_by_name_and_locked(<em>Ryan</em>, true)</tt>. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type <tt>find_by_name(params[:name])</tt> than it is to type <tt>first(:conditions ⇒ ["name = ?", params[:name]])</tt>.</p></div>
<divclass="para"><p>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 <tt>find_or_create_by_name(params[:name])</tt>. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for <tt>Client.find_or_create_by_name(<em>Ryan</em>)</tt>:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p><tt>find_or_create</tt>'s sibling, <tt>find_or_initialize</tt>, will find an object and if it does not exist will call <tt>new</tt> with the parameters you passed in. For example:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>will either assign an existing client object with the name <em>Ryan</em> to the client local variable, or initialize new object similar to calling <tt>Client.new(:name ⇒<em>Ryan</em>)</tt>. From here, you can modify other fields in client by calling the attribute setters on it: <tt>client.locked = true</tt> and when you want to write it to the database just call <tt>save</tt> on it.</p></div>
<divclass="para"><p>If you'd like to use your own SQL to find records a table you can use <tt>find_by_sql</tt>. The <tt>find_by_sql</tt> 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:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p><tt>find_by_sql</tt> provides you with a simple way of making custom calls to the database and retrieving instantiated objects.</p></div>
<divclass="para"><p><tt>find_by_sql</tt> has a close relative called <tt>connection#select_all</tt>. <tt>select_all</tt> will retrieve objects from the database using custom SQL just like <tt>find_by_sql</tt> but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<spanstyle="color: #990000">.</span>connection<spanstyle="color: #990000">.</span>select_all<spanstyle="color: #990000">(</span><spanstyle="color: #FF0000">"SELECT * FROM `clients` WHERE `id` = '1'"</span><spanstyle="color: #990000">)</span>
<divclass="para"><p>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 <tt>Client.find(params[:id]).orders.find_by_sent_and_received(true, false)</tt>. Having this find method available on associations is extremely helpful when using nested controllers.</p></div>
<divclass="para"><p>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.</p></div>
<h3id="_simple_named_scopes">17.1. Simple Named Scopes</h3>
<divclass="para"><p>Suppose want to find all clients who are male. You could use this code:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>Then you could call <tt>Client.males.all</tt> to get all the clients who are male. Please note that if you do not specify the <tt>all</tt> on the end you will get a <tt>Scope</tt> object back, not a set of records which you do get back if you put the <tt>all</tt> on the end.</p></div>
<divclass="para"><p>If you wanted to find all the clients who are active, you could use this:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>You can call this new named_scope with <tt>Client.active.all</tt> and this will do the same query as if we just used <tt>Client.all(:conditions ⇒ ["active = ?", true])</tt>. 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 <tt>Client.active.first</tt>.</p></div>
<h3id="_combining_named_scopes">17.2. Combining Named Scopes</h3>
<divclass="para"><p>If you wanted to find all the clients who are active and male you can stack the named scopes like this:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>If you would then like to do a <tt>all</tt> on that scope, you can. Just like an association, named scopes allow you to call <tt>all</tt> on them:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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, <tt>2.weeks.ago</tt> 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:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>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.</p></div>
<h3id="_named_scopes_with_multiple_models">17.4. Named Scopes with Multiple Models</h3>
<divclass="para"><p>This method, called as <tt>Client.active_within_2_weeks.all</tt>, will return all clients who have placed orders in the past 2 weeks.</p></div>
<h3id="_arguments_to_named_scopes">17.5. Arguments to Named Scopes</h3>
<divclass="para"><p>This will work if you call <tt>Client.recent(2.weeks.ago).all</tt> but not if you call <tt>Client.recent</tt>. If you want to add an optional argument for this, you have to use the splat operator as the block's parameter.</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>This will work with <tt>Client.recent(2.weeks.ago).all</tt> and <tt>Client.recent.all</tt>, with the latter always returning records with a created_at date between right now and 2 weeks ago.</p></div>
<divclass="para"><p>Remember that named scopes are stackable, so you will be able to do <tt>Client.recent(2.weeks.ago).unlocked.all</tt> to find all clients created between right now and 2 weeks ago and have their locked field set to false.</p></div>
<divclass="para"><p>All Active Record models come with a named scope named <tt>scoped</tt>, which allows you to create anonymous scopes. For example:</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.</p></div>
<divclass="para"><p>If you simply want to check for the existence of the object there's a method called <tt>exists?</tt>. 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.</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="para"><p>The <tt>exists?</tt> 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.</p></div>
<divclass="para"><p>This code specifies <tt>clients.first_name</tt> just in case one of the join tables has a field also called <tt>first_name</tt> and it uses <tt>orders.status</tt> because that's the name of our join table.</p></div>
<divclass="para"><p>If you want to see how many records are in your model's table you could call <tt>Client.count</tt> 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 <tt>Client.count(:age)</tt>.</p></div>
<divclass="para"><p>For options, please see the parent section, Calculations.</p></div>
<h3id="_average">19.2. Average</h3>
<divclass="para"><p>If you want to see the average of a certain number in one of your tables you can call the <tt>average</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<divclass="para"><p>This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.</p></div>
<divclass="para"><p>For options, please see the parent section, <ahref="#_calculations">Calculations</a></p></div>
<h3id="_minimum">19.3. Minimum</h3>
<divclass="para"><p>If you want to find the minimum value of a field in your table you can call the <tt>minimum</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<divclass="para"><p>For options, please see the parent section, <ahref="#_calculations">Calculations</a></p></div>
<h3id="_maximum">19.4. Maximum</h3>
<divclass="para"><p>If you want to find the maximum value of a field in your table you can call the <tt>maximum</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<divclass="para"><p>For options, please see the parent section, <ahref="#_calculations">Calculations</a></p></div>
<h3id="_sum">19.5. Sum</h3>
<divclass="para"><p>If you want to find the sum of a field for all records in your table you can call the <tt>sum</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<divclass="para"><p>For options, please see the parent section, <ahref="#_calculations">Calculations</a></p></div>
</div>
<h2id="_credits">20. Credits</h2>
<divclass="sectionbody">
<divclass="para"><p>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.</p></div>
<divclass="para"><p>Thanks to Mike Gunderloy for his tips on creating this guide.</p></div>
October 27, 2008: Fixed up all points specified in <ahref="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6">this comment</a> with an exception of the final point by Ryan Bigg