<li><ahref="#_choosing_between_tt_belongs_to_tt_and_tt_has_one_tt">Choosing Between <tt>belongs_to</tt> and <tt>has_one</tt></a></li>
<li><ahref="#_choosing_between_tt_has_many_through_tt_and_tt_has_and_belongs_to_many_tt">Choosing Between <tt>has_many :through</tt> and <tt>has_and_belongs_to_many</tt></a></li>
<divclass="paragraph"><p>Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:</p></div>
<divclass="paragraph"><p>With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here’s the revised code for setting up customers and orders:</p></div>
<divclass="paragraph"><p>To learn more about the different types of associations, read the next section of this Guide. That’s followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.</p></div>
<divclass="paragraph"><p>In Rails, an <em>association</em> is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model <tt>belongs_to</tt> another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:</p></div>
<divclass="paragraph"><p>In the remainder of this guide, you’ll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.</p></div>
<divclass="paragraph"><p>A <tt>belongs_to</tt> association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you’d declare the order model this way:</p></div>
<divclass="paragraph"><p>A <tt>has_one</tt> association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you’d declare the supplier model like this:</p></div>
<divclass="paragraph"><p>A <tt>has_many</tt> association indicates a one-to-many connection with another model. You’ll often find this association on the "other side" of a <tt>belongs_to</tt> association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:</p></div>
<divclass="paragraph"><p>A <tt>has_many :through</tt> association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding <em>through</em> a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:</p></div>
<divclass="paragraph"><p>The <tt>has_many :through</tt> association is also useful for setting up "shortcuts" through nested :<tt>has_many</tt> associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:</p></div>
<divclass="paragraph"><p>A <tt>has_one :through</tt> association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding <em>through</em> a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:</p></div>
<divclass="paragraph"><p>A <tt>has_and_belongs_to_many</tt> association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:</p></div>
<divclass="paragraph"><p>If you want to set up a 1-1 relationship between two models, you’ll need to add <tt>belongs_to</tt> to one, and <tt>has_one</tt> to the other. How do you know which is which?</p></div>
<divclass="paragraph"><p>The distinction is in where you place the foreign key (it goes on the table for the class declaring the <tt>belongs_to</tt> association), but you should give some thought to the actual meaning of the data as well. The <tt>has_one</tt> relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:</p></div>
<tdclass="content">Using <tt>t.integer :supplier_id</tt> makes the foreign key naming obvious and implicit. In current versions of Rails, you can abstract away this implementation detail by using <tt>t.references :supplier</tt> instead.</td>
</tr></table>
</div>
<h3id="_choosing_between_tt_has_many_through_tt_and_tt_has_and_belongs_to_many_tt">2.8. Choosing Between <tt>has_many :through</tt> and <tt>has_and_belongs_to_many</tt></h3>
<divclass="paragraph"><p>Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use <tt>has_and_belongs_to_many</tt>, which allows you to make the association directly:</p></div>
<divclass="paragraph"><p>The second way to declare a many-to-many relationship is to use <tt>has_many :through</tt>. This makes the association indirectly, through a join model:</p></div>
<divclass="paragraph"><p>The simplest rule of thumb is that you should set up a <tt>has_many :through</tt> relationship if you need to work with the relationship model as an independent entity. If you don’t need to do anything with the relationship model, it may be simpler to set up a <tt>has_and_belongs_to_many</tt> relationship (though you’ll need to remember to create the joining table).</p></div>
<divclass="paragraph"><p>You should use <tt>has_many :through</tt> if you need validations, callbacks, or extra attributes on the join model.</p></div>
<divclass="paragraph"><p>A slightly more advanced twist on associations is the <em>polymorphic association</em>. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here’s how this could be declared:</p></div>
<divclass="paragraph"><p>You can think of a polymorphic <tt>belongs_to</tt> declaration as setting up an interface that any other model can use. From an instance of the <tt>Employee</tt> model, you can retrieve a collection of pictures: <tt>@employee.pictures</tt>. Similarly, you can retrieve <tt>@product.pictures</tt>. If you have an instance of the <tt>Picture</tt> model, you can get to its parent via <tt>@picture.imageable</tt>. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:</p></div>
<divclass="paragraph"><p>In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations:</p></div>
<divclass="paragraph"><p>Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:</p></div>
<divclass="paragraph"><p>All of the association methods are built around caching that keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:</p></div>
<divclass="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>customer<spanstyle="color: #990000">.</span>orders <spanstyle="font-style: italic"><spanstyle="color: #9A1900"># retrieves orders from the database</span></span>
customer<spanstyle="color: #990000">.</span>orders<spanstyle="color: #990000">.</span>size <spanstyle="font-style: italic"><spanstyle="color: #9A1900"># uses the cached copy of orders</span></span>
customer<spanstyle="color: #990000">.</span>orders<spanstyle="color: #990000">.</span>empty? <spanstyle="font-style: italic"><spanstyle="color: #9A1900"># uses the cached copy of orders</span></span></tt></pre></div></div>
<divclass="paragraph"><p>But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass <tt>true</tt> to the association call:</p></div>
<divclass="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>customer<spanstyle="color: #990000">.</span>orders <spanstyle="font-style: italic"><spanstyle="color: #9A1900"># retrieves orders from the database</span></span>
customer<spanstyle="color: #990000">.</span>orders<spanstyle="color: #990000">.</span>size <spanstyle="font-style: italic"><spanstyle="color: #9A1900"># uses the cached copy of orders</span></span>
customer<spanstyle="color: #990000">.</span>orders<spanstyle="color: #990000">(</span><spanstyle="font-weight: bold"><spanstyle="color: #0000FF">true</span></span><spanstyle="color: #990000">).</span>empty? <spanstyle="font-style: italic"><spanstyle="color: #9A1900"># discards the cached copy of orders and goes back to the database</span></span></tt></pre></div></div>
<divclass="paragraph"><p>You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of <tt>ActiveRecord::Base</tt>. The association method would override the base method and break things. For instance, <tt>attributes</tt> or <tt>connection</tt> are bad names for associations.</p></div>
<divclass="paragraph"><p>Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For <tt>belongs_to</tt> associations you need to create foreign keys, and for <tt>has_and_belongs_to_many</tt> associations you need to create the appropriate join table.</p></div>
<h4id="_creating_foreign_keys_for_tt_belongs_to_tt_associations">3.3.1. Creating Foreign Keys for <tt>belongs_to</tt> Associations</h4>
<divclass="paragraph"><p>When you declare a <tt>belongs_to</tt> association, you need to create foreign keys as appropriate. For example, consider this model:</p></div>
<divclass="paragraph"><p>If you create an association some time after you build the underlying model, you need to remember to create an <tt>add_column</tt> migration to provide the necessary foreign key.</p></div>
<h4id="_creating_join_tables_for_tt_has_and_belongs_to_many_tt_associations">3.3.2. Creating Join Tables for <tt>has_and_belongs_to_many</tt> Associations</h4>
<divclass="paragraph"><p>If you create a <tt>has_and_belongs_to_many</tt> association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the <tt>:join_table</tt> option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.</p></div>
<tdclass="content">The precedence between model names is calculated using the <tt><</tt> operator for <tt>String</tt>. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".</td>
<divclass="paragraph"><p>Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:</p></div>
<divclass="paragraph"><p>These need to be backed up by a migration to create the <tt>assemblies_parts</tt> table. This table should be created without a primary key:</p></div>
<divclass="paragraph"><p>By default, associations look for objects only within the current module’s scope. This can be important when you declare Active Record models within a module. For example:</p></div>
<divclass="paragraph"><p>This will work fine, because both the <tt>Supplier</tt> and the <tt>Account</tt> class are defined within the same scope. But this will not work, because <tt>Supplier</tt> and <tt>Account</tt> are defined in different scopes:</p></div>
<divclass="paragraph"><p>To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:</p></div>
<divclass="paragraph"><p>The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.</p></div>
<divclass="paragraph"><p>The <tt>belongs_to</tt> association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use <tt>has_one</tt> instead.</p></div>
<divclass="paragraph"><p>When you declare a <tt>belongs_to</tt> assocation, the declaring class automatically gains five methods related to the association:</p></div>
<divclass="paragraph"><p>In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to <tt>belongs_to</tt>. For example, given the declaration:</p></div>
<divclass="paragraph"><p>The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns <tt>nil</tt>.</p></div>
<divclass="paragraph"><p>If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass <tt>true</tt> as the <tt>force_reload</tt> argument.</p></div>
<divclass="paragraph"><p>The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object’s foreign key to the same value.</p></div>
<divclass="paragraph"><p>The <tt>build<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object’s foreign key will be set, but the associated object will <em>not</em> yet be saved.</p></div>
<divclass="paragraph"><p>The <tt>create<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object’s foreign key will be set. In addition, the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<divclass="paragraph"><p>In many situations, you can use the default behavior of <tt>belongs_to</tt> without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a <tt>belongs_to</tt> association. For example, an association with several options might look like this:</p></div>
<divclass="paragraph"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is <tt>Patron</tt>, you’d set things up this way:</p></div>
<divclass="paragraph"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<divclass="paragraph"><p>The <tt>:counter_cache</tt> option can be used to make finding the number of belonging objects more efficient. Consider these models:</p></div>
<divclass="paragraph"><p>With these declarations, asking for the value of <tt>@customer.orders.size</tt> requires making a call to the database to perform a <tt>COUNT(*)</tt> query. To avoid this call, you can add a counter cache to the <em>belonging</em> model:</p></div>
<divclass="paragraph"><p>With this declaration, Rails will keep the cache value up to date, and then return that value in response to the <tt>.size</tt> method.</p></div>
<divclass="paragraph"><p>Although the <tt>:counter_cache</tt> option is specified on the model that includes the <tt>belongs_to</tt> declaration, the actual column must be added to the <em>associated</em> model. In the case above, you would need to add a column named <tt>orders_count</tt> to the <tt>Customer</tt> model. You can override the default column name if you need to:</p></div>
<divclass="paragraph"><p>Counter cache columns are added to the containing model’s list of read-only attributes through <tt>attr_readonly</tt>.</p></div>
<divclass="paragraph"><p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the destroy method on the associated object to delete that object. If you set the <tt>:dependent</tt> option to <tt>:delete</tt>, then deleting this object will delete the associated object <em>without</em> calling its <tt>destroy</tt> method.</p></div>
<tdclass="content">You should not specify this option on a <tt>belongs_to</tt> association that is connected with a <tt>has_many</tt> association on the other class. Doing so can lead to orphaned records in your database.</td>
<divclass="paragraph"><p>By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<divclass="paragraph"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p></div>
<divclass="paragraph"><p>If you frequently retrieve customers directly from line items (<tt>@line_item.order.customer</tt>), then you can make your code somewhat more efficient by including customers in the association from line items to orders:</p></div>
<tdclass="content">There’s no need to use <tt>:include</tt> for immediate associations - that is, if you have <tt>Order belongs_to :customer</tt>, then the customer is eager-loaded automatically when it’s needed.</td>
<divclass="paragraph"><p>Passing <tt>true</tt> to the <tt>:polymorphic</tt> option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.</p></div>
<divclass="paragraph"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated object will be read-only when retrieved via the association.</p></div>
<divclass="paragraph"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p></div>
<tdclass="content">If you set the <tt>:select</tt> option on a <tt>belongs_to</tt> association, you should also set the <tt>foreign_key</tt> option to guarantee the correct results.</td>
<divclass="paragraph"><p>If you set the <tt>:validate</tt> option to <tt>true</tt>, then associated objects will be validated whenever you save this object. By default, this is <tt>false</tt>: associated objects will not be validated when this object is saved.</p></div>
<divclass="paragraph"><p>Assigning an object to a <tt>belongs_to</tt> association does <em>not</em> automatically save the object. It does not save the associated object either.</p></div>
<divclass="paragraph"><p>The <tt>has_one</tt> association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use <tt>belongs_to</tt> instead.</p></div>
<divclass="paragraph"><p>When you declare a <tt>has_one</tt> association, the declaring class automatically gains five methods related to the association:</p></div>
<divclass="paragraph"><p>In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to <tt>has_one</tt>. For example, given the declaration:</p></div>
<divclass="paragraph"><p>The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns <tt>nil</tt>.</p></div>
<divclass="paragraph"><p>If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass <tt>true</tt> as the <tt>force_reload</tt> argument.</p></div>
<divclass="paragraph"><p>The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object’s foreign key to the same value.</p></div>
<divclass="paragraph"><p>The <tt>build<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will <em>not</em> yet be saved.</p></div>
<divclass="paragraph"><p>The <tt>create<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<divclass="paragraph"><p>In many situations, you can use the default behavior of <tt>has_one</tt> without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a <tt>has_one</tt> association. For example, an association with several options might look like this:</p></div>
<divclass="paragraph"><p>Setting the <tt>:as</tt> option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.</p></div>
<divclass="paragraph"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you’d set things up this way:</p></div>
<divclass="paragraph"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<divclass="paragraph"><p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the destroy method on the associated object to delete that object. If you set the <tt>:dependent</tt> option to <tt>:delete</tt>, then deleting this object will delete the associated object <em>without</em> calling its <tt>destroy</tt> method. If you set the <tt>:dependent</tt> option to <tt>:nullify</tt>, then deleting this object will set the foreign key in the association object to <tt>NULL</tt>.</p></div>
<divclass="paragraph"><p>By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<divclass="paragraph"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p></div>
<divclass="paragraph"><p>If you frequently retrieve representatives directly from suppliers (<tt>@supplier.account.representative</tt>), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:</p></div>
<divclass="paragraph"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause). Because a <tt>has_one</tt> association will only retrieve a single associated object, this option should not be needed.</p></div>
<divclass="paragraph"><p>By convention, Rails guesses that the column used to hold the primary key of this model is <tt>id</tt>. You can override this and explicitly specify the primary key with the <tt>:primary_key</tt> option.</p></div>
<divclass="paragraph"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated object will be read-only when retrieved via the association.</p></div>
<divclass="paragraph"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p></div>
<divclass="paragraph"><p>The <tt>:source_type</tt> option specifies the source association type for a <tt>has_one :through</tt> association that proceeds through a polymorphic association.</p></div>
<divclass="paragraph"><p>The <tt>:through</tt> option specifies a join model through which to perform the query. <tt>has_one :through</tt> associations are discussed in detail later in this guide.</p></div>
<divclass="paragraph"><p>If you set the <tt>:validate</tt> option to <tt>true</tt>, then associated objects will be validated whenever you save this object. By default, this is <tt>false</tt>: associated objects will not be validated when this object is saved.</p></div>
<divclass="paragraph"><p>When you assign an object to a <tt>has_one</tt> association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.</p></div>
<divclass="paragraph"><p>If either of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p></div>
<divclass="paragraph"><p>If the parent object (the one declaring the <tt>has_one</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) then the child objects are not saved.</p></div>
<divclass="paragraph"><p>If you want to assign an object to a <tt>has_one</tt> association without saving the object, use the <tt>association.build</tt> method.</p></div>
<divclass="paragraph"><p>The <tt>has_many</tt> association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.</p></div>
<divclass="paragraph"><p>When you declare a <tt>has_many</tt> association, the declaring class automatically gains 13 methods related to the association:</p></div>
<divclass="paragraph"><p>In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to <tt>has_many</tt>, and <tt><em>collection\_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration:</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to <tt>NULL</tt>.</p></div>
<tdclass="content">Objects will be in addition destroyed if they’re associated with <tt>:dependent => :destroy</tt>, and deleted if they’re associated with <tt>:dependent => :delete_all</tt>.</td>
<divclass="paragraph"><p>The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p></div>
<divclass="paragraph"><p>The <tt><em>collection\_singular</em>\_ids</tt> method returns an array of the ids of the objects in the collection.</p></div>
<divclass="paragraph"><p>The <tt><em>_collection\_singular</em>\_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the database if <tt>:dependent => :delete_all</tt>, and otherwise sets their foreign keys to <tt>NULL</tt>.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.empty?</tt> method returns <tt>true</tt> if the collection does not contain any associated objects.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.find</tt>.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.exists?</tt>.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will <em>not</em> yet be saved.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<divclass="paragraph"><p>In many situations, you can use the default behavior for <tt>has_many</tt> without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a <tt>has_many</tt> association. For example, an association with several options might look like this:</p></div>
<divclass="paragraph"><p>Setting the <tt>:as</tt> option indicates that this is a polymorphic association, as discussed earlier in this guide.</p></div>
<divclass="paragraph"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is <tt>Transaction</tt>, you’d set things up this way:</p></div>
<divclass="paragraph"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<divclass="paragraph"><p>If you use a hash-style <tt>:conditions</tt> option, then record creation via this association will be automatically scoped using the hash. In this case, using <tt>@customer.confirmed_orders.create</tt> or <tt>@customer.confirmed_orders.build</tt> will create orders where the confirmed column has the value <tt>true</tt>.</p></div>
<divclass="paragraph"><p>Normally Rails automatically generates the proper SQL to count the association members. With the <tt>:counter_sql</tt> option, you can specify a complete SQL statement to count them yourself.</p></div>
<tdclass="content">If you specify <tt>:finder_sql</tt> but not <tt>:counter_sql</tt>, then the counter SQL will be generated by substituting <tt>SELECT COUNT(*) FROM</tt> for the <tt>SELECT ... FROM</tt> clause of your <tt>:finder_sql</tt> statement.</td>
<divclass="paragraph"><p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the <tt>:dependent</tt> option to <tt>:delete_all</tt>, then deleting this object will delete the associated objects <em>without</em> calling their <tt>destroy</tt> method. If you set the <tt>:dependent</tt> option to <tt>:nullify</tt>, then deleting this object will set the foreign key in the associated objects to <tt>NULL</tt>.</p></div>
<divclass="paragraph"><p>The <tt>:extend</tt> option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.</p></div>
<divclass="paragraph"><p>Normally Rails automatically generates the proper SQL to fetch the association members. With the <tt>:finder_sql</tt> option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.</p></div>
<divclass="paragraph"><p>By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<divclass="paragraph"><p>The <tt>:group</tt> option supplies an attribute name to group the result set by, using a <tt>GROUP BY</tt> clause in the finder SQL.</p></div>
<divclass="paragraph"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p></div>
<divclass="paragraph"><p>If you frequently retrieve line items directly from customers (<tt>@customer.orders.line_items</tt>), then you can make your code somewhat more efficient by including line items in the association from customers to orders:</p></div>
<divclass="paragraph"><p>The <tt>:limit</tt> option lets you restrict the total number of objects that will be fetched through an association.</p></div>
<divclass="paragraph"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset => 11</tt>, it will skip the first 11 records.</p></div>
<divclass="paragraph"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause).</p></div>
<divclass="paragraph"><p>By convention, Rails guesses that the column used to hold the primary key of this model is <tt>id</tt>. You can override this and explicitly specify the primary key with the <tt>:primary_key</tt> option.</p></div>
<divclass="paragraph"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated objects will be read-only when retrieved via the association.</p></div>
<divclass="paragraph"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p></div>
<tdclass="content">If you specify your own <tt>:select</tt>, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.</td>
<divclass="paragraph"><p>The <tt>:source</tt> option specifies the source association name for a <tt>has_many :through</tt> association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.</p></div>
<divclass="paragraph"><p>The <tt>:source_type</tt> option specifies the source association type for a <tt>has_many :through</tt> association that proceeds through a polymorphic association.</p></div>
<divclass="paragraph"><p>The <tt>:through</tt> option specifies a join model through which to perform the query. <tt>has_many :through</tt> associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.</p></div>
<divclass="paragraph"><p>Specify the <tt>:uniq => true</tt> option to remove duplicates from the collection. This is most useful in conjunction with the <tt>:through</tt> option.</p></div>
<divclass="paragraph"><p>If you set the <tt>:validate</tt> option to <tt>false</tt>, then associated objects will not be validated whenever you save this object. By default, this is <tt>true</tt>: associated objects will be validated when this object is saved.</p></div>
<divclass="paragraph"><p>When you assign an object to a <tt>has_many</tt> association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.</p></div>
<divclass="paragraph"><p>If any of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p></div>
<divclass="paragraph"><p>If the parent object (the one declaring the <tt>has_many</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.</p></div>
<divclass="paragraph"><p>If you want to assign an object to a <tt>has_many</tt> association without saving the object, use the <tt><em>collection</em>.build</tt> method.</p></div>
<divclass="paragraph"><p>The <tt>has_and_belongs_to_many</tt> association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.</p></div>
<divclass="paragraph"><p>When you declare a <tt>has_and_belongs_to_many</tt> association, the declaring class automatically gains 13 methods related to the association:</p></div>
<divclass="paragraph"><p>In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to <tt>has_many</tt>, and <tt><em>collection</em>\_singular</tt> is replaced with the singularized version of that symbol.. For example, given the declaration:</p></div>
<divclass="paragraph"><p>If the join table for a <tt>has_and_belongs_to_many</tt> association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.</p></div>
<tdclass="content">The use of extra attributes on the join table in a <tt>has_and_belongs_to_many</tt> association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a <tt>has_many :through</tt> association instead of <tt>has_and_belongs_to_many</tt>.</td>
<divclass="paragraph"><p>The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p></div>
<divclass="paragraph"><p># Returns an array of the associated objects' ids</p></div>
<divclass="paragraph"><p>The <tt><em>collection\_singular</em>\_ids</tt> method returns an array of the ids of the objects in the collection.</p></div>
<divclass="paragraph"><p>The <tt><em>collection\_singular</em>\_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining tableassociation. This does not destroy the associated objects.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.empty?</tt> method returns <tt>true</tt> if the collection does not contain any associated objects.</p></div>
<divclass="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><spanstyle="color: #FF0000"><% if @part.assemblies.empty? %></span>
This part is <spanstyle="font-weight: bold"><spanstyle="color: #0000FF">not</span></span> used <spanstyle="font-weight: bold"><spanstyle="color: #0000FF">in</span></span> any assemblies
<divclass="paragraph"><p>The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.find</tt>. It also adds the additional condition that the object must be in the collection.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.exists?</tt>.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.build</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will <em>not</em> yet be saved.</p></div>
<divclass="paragraph"><p>The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This objects will be instantiated from the passed attributes, the link through the join table will be created, and the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<divclass="paragraph"><p>In many situations, you can use the default behavior for <tt>has_and_belongs_to_many</tt> without any customization. But you can alter that behavior in a number of ways. This section cover the options that you can pass when you create a <tt>has_and_belongs_to_many</tt> association. For example, an association with several options might look like this:</p></div>
<divclass="paragraph"><p>By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix <tt>_id</tt> added. The <tt>:association_foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<tdclass="content">The <tt>:foreign_key</tt> and <tt>:association_foreign_key</tt> options are useful when setting up a many-to-many self-join. For example:</td>
</tr></table>
</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><spanstyle="font-weight: bold"><spanstyle="color: #0000FF">class</span></span> User <spanstyle="color: #990000"><</span> ActiveRecord<spanstyle="color: #990000">::</span>Base
<divclass="paragraph"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is <tt>Gadget</tt>, you’d set things up this way:</p></div>
<divclass="paragraph"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<divclass="paragraph"><p>If you use a hash-style <tt>:conditions</tt> option, then record creation via this association will be automatically scoped using the hash. In this case, using <tt>@parts.assemblies.create</tt> or <tt>@parts.assemblies.build</tt> will create orders where the factory column has the value "Seattle".</p></div>
<divclass="paragraph"><p>Normally Rails automatically generates the proper SQL to count the association members. With the <tt>:counter_sql</tt> option, you can specify a complete SQL statement to count them yourself.</p></div>
<tdclass="content">If you specify <tt>:finder_sql</tt> but not <tt>:counter_sql</tt>, then the counter SQL will be generated by substituting <tt>SELECT COUNT(*) FROM</tt> for the <tt>SELECT ... FROM</tt> clause of your <tt>:finder_sql</tt> statement.</td>
<divclass="paragraph"><p>Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the <tt>:delete_sql</tt> option, you can specify a complete SQL statement to delete them yourself.</p></div>
<divclass="paragraph"><p>The <tt>:extend</tt> option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.</p></div>
<divclass="paragraph"><p>Normally Rails automatically generates the proper SQL to fetch the association members. With the <tt>:finder_sql</tt> option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.</p></div>
<divclass="paragraph"><p>By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<divclass="paragraph"><p>The <tt>:group</tt> option supplies an attribute name to group the result set by, using a <tt>GROUP BY</tt> clause in the finder SQL.</p></div>
<divclass="paragraph"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.</p></div>
<divclass="paragraph"><p>Normally Rails automatically generates the proper SQL to create links between the associated classes. With the <tt>:insert_sql</tt> option, you can specify a complete SQL statement to insert them yourself.</p></div>
<divclass="paragraph"><p>If the default name of the join table, based on lexical ordering, is not what you want, you can use the <tt>:join_table</tt> option to override the default.</p></div>
<divclass="paragraph"><p>The <tt>:limit</tt> option lets you restrict the total number of objects that will be fetched through an association.</p></div>
<divclass="paragraph"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset => 11</tt>, it will skip the first 11 records.</p></div>
<divclass="paragraph"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause).</p></div>
<divclass="paragraph"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated objects will be read-only when retrieved via the association.</p></div>
<divclass="paragraph"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p></div>
<divclass="paragraph"><p>If you set the <tt>:validate</tt> option to <tt>false</tt>, then associated objects will not be validated whenever you save this object. By default, this is <tt>true</tt>: associated objects will be validated when this object is saved.</p></div>
<divclass="paragraph"><p>When you assign an object to a <tt>has_and_belongs_to_many</tt> association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.</p></div>
<divclass="paragraph"><p>If any of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p></div>
<divclass="paragraph"><p>If the parent object (the one declaring the <tt>has_and_belongs_to_many</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.</p></div>
<divclass="paragraph"><p>If you want to assign an object to a <tt>has_and_belongs_to_many</tt> association without saving the object, use the <tt><em>collection</em>.build</tt> method.</p></div>
<divclass="paragraph"><p>Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a <tt>:before_save</tt> callback to cause something to happen just before an object is saved.</p></div>
<divclass="paragraph"><p>Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:</p></div>
<divclass="paragraph"><p>If a <tt>before_add</tt> callback throws an exception, the object does not get added to the collection. Similarly, if a <tt>before_remove</tt> callback throws an exception, the object does not get removed from the collection.</p></div>
<divclass="paragraph"><p>You’re not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:</p></div>
<divclass="paragraph"><p>If you have an extension that should be shared by many associations, you can use a named extension module. For example:</p></div>
<tt>proxy_owner</tt> returns the object that the association is a part of.
</p>
</li>
<li>
<p>
<tt>proxy_reflection</tt> returns the reflection object that describes the association.
</p>
</li>
<li>
<p>
<tt>proxy_target</tt> returns the associated object for <tt>belongs_to</tt> or <tt>has_one</tt>, or the collection of associated objects for <tt>has_many</tt> or <tt>has_and_belongs_to_many</tt>.
September 28, 2008: Corrected <tt>has_many :through</tt> diagram, added polymorphic diagram, some reorganization by <ahref="../authors.html#mgunderloy">Mike Gunderloy</a> . First release version.
</p>
</li>
<li>
<p>
September 22, 2008: Added diagrams, misc. cleanup by <ahref="../authors.html#mgunderloy">Mike Gunderloy</a> (not yet approved for publication)
</p>
</li>
<li>
<p>
September 14, 2008: initial version by <ahref="../authors.html#mgunderloy">Mike Gunderloy</a> (not yet approved for publication)