diff options
Diffstat (limited to 'railties/guides/source/association_basics.textile')
-rw-r--r-- | railties/guides/source/association_basics.textile | 381 |
1 files changed, 190 insertions, 191 deletions
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index e82f32d35e..3c03c825cd 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -37,7 +37,7 @@ end @customer.destroy </ruby> -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: +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: <ruby> class Customer < ActiveRecord::Base @@ -61,7 +61,7 @@ Deleting a customer and all of its orders is _much_ easier: @customer.destroy </ruby> -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. +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. h3. The Types of Associations @@ -76,7 +76,7 @@ In Rails, an _association_ is a connection between two Active Record models. Ass 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. -h4. The belongs_to Association +h4. The +belongs_to+ association A +belongs_to+ 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: @@ -88,7 +88,7 @@ end !images/belongs_to.png(belongs_to Association Diagram)! -h4. The has_one Association +h4. The +has_one+ association A +has_one+ 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: @@ -100,7 +100,7 @@ end !images/has_one.png(has_one Association Diagram)! -h4. The has_many Association +h4. The +has_many+ association A +has_many+ association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a +belongs_to+ 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: @@ -114,7 +114,7 @@ NOTE: The name of the other model is pluralized when declaring a +has_many+ asso !images/has_many.png(has_many Association Diagram)! -h4. The has_many :through Association +h4. The +has_many :through+ association A +has_many :through+ 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 _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this: @@ -155,7 +155,7 @@ class Paragraph < ActiveRecord::Base end </ruby> -h4. The has_one :through Association +h4. The +has_one :through+ association A +has_one :through+ 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 _through_ 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: @@ -177,7 +177,7 @@ end !images/has_one_through.png(has_one :through Association Diagram)! -h4. The has_and_belongs_to_many Association +h4. The +has_and_belongs_to_many+ association A +has_and_belongs_to_many+ 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: @@ -193,7 +193,7 @@ end !images/habtm.png(has_and_belongs_to_many Association Diagram)! -h4. Choosing Between belongs_to and has_one +h4. Choosing between +belongs_to+ and +has_one+ If you want to set up a 1–1 relationship between two models, you'll need to add +belongs_to+ to one, and +has_one+ to the other. How do you know which is which? @@ -235,7 +235,7 @@ end NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead. -h4. Choosing Between has_many :through and has_and_belongs_to_many +h4. Choosing between +has_many :through+ and +has_and_belongs_to_many+ Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use +has_and_belongs_to_many+, which allows you to make the association directly: @@ -272,7 +272,7 @@ The simplest rule of thumb is that you should set up a +has_many :through+ relat You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model. -h4. Polymorphic Associations +h4. Polymorphic associations A slightly more advanced twist on associations is the _polymorphic association_. 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: @@ -319,7 +319,7 @@ This migration can be simplified by using the +t.references+ form: class CreatePictures < ActiveRecord::Migration def self.up create_table :pictures do |t| - t.string :name + t.string :name t.references :imageable, :polymorphic => true t.timestamps end @@ -333,7 +333,7 @@ end !images/polymorphic.png(Polymorphic Association Diagram)! -h4. Self Joins +h4. Self joins 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 between manager and subordinates. This situation can be modeled with self-joining associations: @@ -356,7 +356,7 @@ Here are a few things you should know to make efficient use of Active Record ass * Updating the schema * Controlling association scope -h4. Controlling Caching +h4. Controlling caching All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example: @@ -375,15 +375,15 @@ customer.orders(true).empty? # discards the cached copy of orders # and goes back to the database </ruby> -h4. Avoiding Name Collisions +h4. Avoiding name collisions 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 +ActiveRecord::Base+. The association method would override the base method and break things. For instance, +attributes+ or +connection+ are bad names for associations. -h4. Updating the Schema +h4. Updating the schema 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 +belongs_to+ associations you need to create foreign keys, and for +has_and_belongs_to_many+ associations you need to create the appropriate join table. -h5. Creating Foreign Keys for belongs_to Associations +h5. Creating foreign Keys for +belongs_to+ associations When you declare a +belongs_to+ association, you need to create foreign keys as appropriate. For example, consider this model: @@ -399,9 +399,9 @@ This declaration needs to be backed up by the proper foreign key declaration on class CreateOrders < ActiveRecord::Migration def self.up create_table :orders do |t| - t.datetime :order_date - t.string :order_number - t.integer :customer_id + t.datetime :order_date + t.string :order_number + t.integer :customer_id end end @@ -413,7 +413,7 @@ end If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key. -h5. Creating Join Tables for has_and_belongs_to_many Associations +h5. Creating join tables for +has_and_belongs_to_many+ associations If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record creates 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. @@ -448,7 +448,9 @@ class CreateAssemblyPartJoinTable < ActiveRecord::Migration end </ruby> -h4. Controlling Association Scope +We pass +:id => false+ to +create_table+ because that table does not represent a model. That's required for the association to work properly. If you observe any strange behaviour in a +has_and_belongs_to_many+ association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit. + +h4. Controlling association scope 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: @@ -484,7 +486,7 @@ module MyApplication end </ruby> -To associate a model with a model in a different scope, you must specify the complete class name in your association declaration: +To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration: <ruby> module MyApplication @@ -508,17 +510,16 @@ h3. Detailed Association Reference 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. -h4. belongs_to Association Reference +h4. +belongs_to+ association reference The +belongs_to+ 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 +has_one+ instead. -h5. Methods Added by belongs_to +h5. Methods added by +belongs_to+ -When you declare a +belongs_to+ association, the declaring class automatically gains five methods related to the association: +When you declare a +belongs_to+ association, the declaring class automatically gains four methods related to the association: * <tt><em>association</em>(force_reload = false)</tt> * <tt><em>association</em>=(associate)</tt> -* <tt><em>association</em>.nil?</tt> * <tt>build_<em>association</em>(attributes = {})</tt> * <tt>create_<em>association</em>(attributes = {})</tt> @@ -535,7 +536,6 @@ Each instance of the order model will have these methods: <ruby> customer customer= -customer.nil? build_customer create_customer </ruby> @@ -558,23 +558,13 @@ The <tt><em>association</em>=</tt> method assigns an associated object to this o @order.customer = @customer </ruby> -h6. _association_.nil? - -The <tt><em>association</em>.nil?</tt> method returns +true+ if there is no associated object. - -<ruby> -if @order.customer.nil? - @msg = "No customer found for this order" -end -</ruby> - h6. build_<em>association</em>(attributes = {}) 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 _not_ yet be saved. <ruby> -@customer = @order.build_customer({:customer_number => 123, - :customer_name => "John Doe"}) +@customer = @order.build_customer(:customer_number => 123, + :customer_name => "John Doe") </ruby> h6. create_<em>association</em>(attributes = {}) @@ -582,11 +572,12 @@ h6. create_<em>association</em>(attributes = {}) 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 _will_ be saved (assuming that it passes any validations). <ruby> -@customer = @order.create_customer({:customer_number => 123, - :customer_name => "John Doe"}) +@customer = @order.create_customer(:customer_number => 123, + :customer_name => "John Doe") </ruby> -h5. Options for belongs_to + +h5. Options for +belongs_to+ In many situations, you can use the default behavior of +belongs_to+ 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 +belongs_to+ association. For example, an association with several options might look like this: @@ -611,11 +602,11 @@ The +belongs_to+ association supports these options: * +:select+ * +:validate+ -h6. :autosave +h6. +:autosave+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. -h6. :class_name +h6. +:class_name+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ 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 +Patron+, you'd set things up this way: @@ -625,7 +616,7 @@ class Order < ActiveRecord::Base end </ruby> -h6. :conditions +h6. +:conditions+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). @@ -635,7 +626,7 @@ class Order < ActiveRecord::Base end </ruby> -h6. :counter_cache +h6. +:counter_cache+ The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models: @@ -659,7 +650,7 @@ class Customer < ActiveRecord::Base end </ruby> -With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +.size+ method. +With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +size+ method. Although the +:counter_cache+ option is specified on the model that includes the +belongs_to+ declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named +orders_count+ to the +Customer+ model. You can override the default column name if you need to: @@ -674,13 +665,13 @@ end Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+. -h6. :dependent +h6. +:dependent+ -If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. +If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database. -h6. :foreign_key +h6. +:foreign_key+ 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 +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: @@ -693,7 +684,7 @@ end TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. -h6. :include +h6. +:include+ 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: @@ -731,39 +722,48 @@ end NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed. -h6. :polymorphic +h6. +:polymorphic+ -Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>. +Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphicassociations">earlier in this guide</a>. -h6. :readonly +h6. +:readonly+ If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association. -h6. :select +h6. +:select+ The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns. TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results. -h6. :validate +h6. +:validate+ If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved. -h5. When are Objects Saved? +h5. How to know whether there's an associated object? + +To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>: + +<ruby> +if @order.customer.nil? + @msg = "No customer found for this order" +end +</ruby> + +h5. When are objects saved? Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either. -h4. has_one Association Reference +h4. +has_one+ association reference The +has_one+ 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 +belongs_to+ instead. -h5. Methods Added by has_one +h5. Methods added by +has_one+ -When you declare a +has_one+ association, the declaring class automatically gains five methods related to the association: +When you declare a +has_one+ association, the declaring class automatically gains four methods related to the association: * <tt><em>association</em>(force_reload = false)</tt> * <tt><em>association</em>=(associate)</tt> -* <tt><em>association</em>.nil?</tt> * <tt>build_<em>association</em>(attributes = {})</tt> * <tt>create_<em>association</em>(attributes = {})</tt> @@ -780,12 +780,11 @@ Each instance of the +Supplier+ model will have these methods: <ruby> account account= -account.nil? build_account create_account </ruby> -h6. <em>association</em>(force_reload = false) +h6. <tt><em>association</em>(force_reload = false)</tt> The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+. @@ -795,7 +794,7 @@ The <tt><em>association</em></tt> method returns the associated object, if any. 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 +true+ as the +force_reload+ argument. -h6. <em>association</em>=(associate) +h6. <tt><em>association</em>=(associate)</tt> 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. @@ -803,33 +802,23 @@ The <tt><em>association</em>=</tt> method assigns an associated object to this o @supplier.account = @account </ruby> -h6. <em>association</em>.nil? - -The <tt><em>association</em>.nil?</tt> method returns +true+ if there is no associated object. - -<ruby> -if @supplier.account.nil? - @msg = "No account found for this supplier" -end -</ruby> - -h6. build_<em>association</em>(attributes = {}) +h6. <tt>build_<em>association</em>(attributes = {})</tt> 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 _not_ yet be saved. <ruby> -@account = @supplier.build_account({:terms => "Net 30"}) +@account = @supplier.build_account(:terms => "Net 30") </ruby> -h6. create_<em>association</em>(attributes = {}) +h6. <tt>create_<em>association</em>(attributes = {})</tt> 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 _will_ be saved (assuming that it passes any validations). <ruby> -@account = @supplier.create_account({:terms => "Net 30"}) +@account = @supplier.create_account(:terms => "Net 30") </ruby> -h5. Options for has_one +h5. Options for +has_one+ In many situations, you can use the default behavior of +has_one+ 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 +has_one+ association. For example, an association with several options might look like this: @@ -857,17 +846,17 @@ The +has_one+ association supports these options: * +:through+ * +:validate+ -h6. :as +h6. +:as+ -Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>. +Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphicassociations">earlier in this guide</a>. -h6. :autosave +h6. +:autosave+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. -h6. :class_name +h6. +:class_name+ -If the name of the other model cannot be derived from the association name, you can use the +:class_name+ 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: +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ 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: <ruby> class Supplier < ActiveRecord::Base @@ -875,7 +864,7 @@ class Supplier < ActiveRecord::Base end </ruby> -h6. :conditions +h6. +:conditions+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). @@ -885,11 +874,11 @@ class Supplier < ActiveRecord::Base end </ruby> -h6. :dependent +h6. +:dependent+ -If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+. +If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+. -h6. :foreign_key +h6. +:foreign_key+ 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 +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: @@ -901,7 +890,7 @@ end TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. -h6. :include +h6. +:include+ 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: @@ -937,53 +926,63 @@ class Representative < ActiveRecord::Base end </ruby> -h6. :order +h6. +:order+ The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed. -h6. :primary_key +h6. +:primary_key+ By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option. -h6. :readonly +h6. +:readonly+ If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association. -h6. :select +h6. +:select+ The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns. -h6. :source +h6. +:source+ The +:source+ option specifies the source association name for a +has_one :through+ association. -h6. :source_type +h6. +:source_type+ The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association. h6. :through -The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#thehas-onethrough-association">earlier in this guide</a>. +The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#thehas-onethroughassociation">earlier in this guide</a>. -h6. :validate +h6. +:validate+ If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved. -h5. When are Objects Saved? +h5. How to know whether there's an associated object? + +To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>: + +<ruby> +if @supplier.account.nil? + @msg = "No account found for this supplier" +end +</ruby> + +h5. When are objects saved? When you assign an object to a +has_one+ 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. If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled. -If the parent object (the one declaring the +has_one+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved. +If the parent object (the one declaring the +has_one+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved. They will automatically when the parent object is saved. If you want to assign an object to a +has_one+ association without saving the object, use the <tt><em>association</em>.build</tt> method. -h4. has_many Association Reference +h4. +has_many+ association reference The +has_many+ 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. -h5. Methods Added +h5. Methods added When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association: @@ -1027,7 +1026,7 @@ orders.build(attributes = {}, ...) orders.create(attributes = {}) </ruby> -h6. <em>collection</em>(force_reload = false) +h6. <tt><em>collection</em>(force_reload = false)</tt> 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. @@ -1035,7 +1034,7 @@ The <tt><em>collection</em></tt> method returns an array of all of the associate @orders = @customer.orders </ruby> -h6. <em>collection</em><<(object, ...) +h6. <tt><em>collection</em><<(object, ...)</tt> 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. @@ -1043,7 +1042,7 @@ The <tt><em>collection</em><<</tt> method adds one or more objects to the collec @customer.orders << @order1 </ruby> -h6. <em>collection</em>.delete(object, ...) +h6. <tt><em>collection</em>.delete(object, ...)</tt> The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to +NULL+. @@ -1054,11 +1053,11 @@ The <tt><em>collection</em>.delete</tt> method removes one or more objects from WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+. -h6. <em>collection</em>=objects +h6. <tt><em>collection</em>=objects</tt> The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate. -h6. <em>collection_singular</em>_ids +h6. <tt><em>collection_singular</em>_ids</tt> The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection. @@ -1066,15 +1065,15 @@ The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids @order_ids = @customer.order_ids </ruby> -h6. <em>collection_singular</em>_ids=ids +h6. <tt><em>collection_singular</em>_ids=ids</tt> 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. -h6. <em>collection</em>.clear +h6. <tt><em>collection</em>.clear</tt> The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+. -h6. <em>collection</em>.empty? +h6. <tt><em>collection</em>.empty?</tt> The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects. @@ -1084,7 +1083,7 @@ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection <% end %> </ruby> -h6. <em>collection</em>.size +h6. <tt><em>collection</em>.size</tt> The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection. @@ -1092,7 +1091,7 @@ The <tt><em>collection</em>.size</tt> method returns the number of objects in th @order_count = @customer.orders.size </ruby> -h6. <em>collection</em>.find(...) +h6. <tt><em>collection</em>.find(...)</tt> The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. @@ -1100,29 +1099,29 @@ The <tt><em>collection</em>.find</tt> method finds objects within the collection @open_orders = @customer.orders.find(:all, :conditions => "open = 1") </ruby> -h6. <em>collection</em>.exist?(...) +h6. <tt><em>collection</em>.exist?(...)</tt> 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 +ActiveRecord::Base.exists?+. -h6. <em>collection</em>.build(attributes = {}, ...) +h6. <tt><em>collection</em>.build(attributes = {}, ...)</tt> 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 _not_ yet be saved. <ruby> -@order = @customer.orders.build({:order_date => Time.now, - :order_number => "A12345"}) +@order = @customer.orders.build(:order_date => Time.now, + :order_number => "A12345") </ruby> -h6. <em>collection</em>.create(attributes = {}) +h6. <tt><em>collection</em>.create(attributes = {})</tt> 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 _will_ be saved (assuming that it passes any validations). <ruby> -@order = @customer.orders.create({:order_date => Time.now, - :order_number => "A12345"}) +@order = @customer.orders.create(:order_date => Time.now, + :order_number => "A12345") </ruby> -h5. Options for has_many +h5. Options for +has_many+ In many situations, you can use the default behavior for +has_many+ 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 +has_many+ association. For example, an association with several options might look like this: @@ -1157,15 +1156,15 @@ The +has_many+ association supports these options: * +:uniq+ * +:validate+ -h6. :as +h6. +:as+ -Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>. +Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphicassociations">earlier in this guide</a>. -h6. :autosave +h6. +:autosave+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. -h6. :class_name +h6. +:class_name+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way: @@ -1175,7 +1174,7 @@ class Customer < ActiveRecord::Base end </ruby> -h6. :conditions +h6. +:conditions+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). @@ -1197,27 +1196,27 @@ end If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+. -h6. :counter_sql +h6. +:counter_sql+ Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself. NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement. -h6. :dependent +h6. +:dependent+ -If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+. +If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+. NOTE: This option is ignored when you use the +:through+ option on the association. -h6. :extend +h6. +:extend+ -The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>. +The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#associationextensions">later in this guide</a>. -h6. :finder_sql +h6. +:finder_sql+ Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary. -h6. :foreign_key +h6. +:foreign_key+ 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 +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: @@ -1229,7 +1228,7 @@ end TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations. -h6. :group +h6. +:group+ The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL. @@ -1239,7 +1238,7 @@ class Customer < ActiveRecord::Base end </ruby> -h6. :include +h6. +:include+ 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: @@ -1275,7 +1274,7 @@ class LineItem < ActiveRecord::Base end </ruby> -h6. :limit +h6. +:limit+ The +:limit+ option lets you restrict the total number of objects that will be fetched through an association. @@ -1286,11 +1285,11 @@ class Customer < ActiveRecord::Base end </ruby> -h6. :offset +h6. +:offset+ The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. -h6. :order +h6. +:order+ The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). @@ -1300,41 +1299,41 @@ class Customer < ActiveRecord::Base end </ruby> -h6. :primary_key +h6. +:primary_key+ -By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option. +By convention, Rails guesses that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option. -h6. :readonly +h6. +:readonly+ If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association. -h6. :select +h6. +:select+ The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns. WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error. -h6. :source +h6. +:source+ The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name. -h6. :source_type +h6. +:source_type+ The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association. -h6. :through +h6. +:through+ -The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#thehas-manythrough-association">earlier in this guide</a>. +The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#thehas-manythroughassociation">earlier in this guide</a>. -h6. :uniq +h6. +:uniq+ Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option. -h6. :validate +h6. +:validate+ If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved. -h5. When are Objects Saved? +h5. When are objects saved? When you assign an object to a +has_many+ 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. @@ -1344,11 +1343,11 @@ If the parent object (the one declaring the +has_many+ association) is unsaved ( If you want to assign an object to a +has_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method. -h4. has_and_belongs_to_many Association Reference +h4. +has_and_belongs_to_many+ association reference The +has_and_belongs_to_many+ 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. -h5. Methods Added +h5. Methods added When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association: @@ -1392,14 +1391,14 @@ assemblies.build(attributes = {}, ...) assemblies.create(attributes = {}) </ruby> -h6. Additional Column Methods +h6. Additional column methods If the join table for a +has_and_belongs_to_many+ 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. WARNING: The use of extra attributes on the join table in a +has_and_belongs_to_many+ 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 +has_many :through+ association instead of +has_and_belongs_to_many+. -h6. <em>collection</em>(force_reload = false) +h6. <tt><em>collection</em>(force_reload = false)</tt> 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. @@ -1407,7 +1406,7 @@ The <tt><em>collection</em></tt> method returns an array of all of the associate @assemblies = @part.assemblies </ruby> -h6. <em>collection</em><<(object, ...) +h6. <tt><em>collection</em><<(object, ...)</tt> The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table. @@ -1417,7 +1416,7 @@ The <tt><em>collection</em><<</tt> method adds one or more objects to the collec NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>. -h6. <em>collection</em>.delete(object, ...) +h6. <tt><em>collection</em>.delete(object, ...)</tt> 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. @@ -1425,11 +1424,11 @@ The <tt><em>collection</em>.delete</tt> method removes one or more objects from @part.assemblies.delete(@assembly1) </ruby> -h6. <em>collection</em>=objects +h6. <tt><em>collection</em>=objects</tt> The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate. -h6. <em>collection_singular</em>_ids +h6. <tt><em>collection_singular</em>_ids</tt> The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection. @@ -1437,15 +1436,15 @@ The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids @assembly_ids = @part.assembly_ids </ruby> -h6. <em>collection_singular</em>_ids=ids +h6. <tt><em>collection_singular</em>_ids=ids</tt> 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. -h6. <em>collection</em>.clear +h6. <tt><em>collection</em>.clear</tt> The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects. -h6. <em>collection</em>.empty? +h6. <tt><em>collection</em>.empty?</tt> The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects. @@ -1455,7 +1454,7 @@ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection <% end %> </ruby> -h6. <em>collection</em>.size +h6. <tt><em>collection</em>.size</tt> The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection. @@ -1463,7 +1462,7 @@ The <tt><em>collection</em>.size</tt> method returns the number of objects in th @assembly_count = @part.assemblies.size </ruby> -h6. <em>collection</em>.find(...) +h6. <tt><em>collection</em>.find(...)</tt> The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection. @@ -1472,11 +1471,11 @@ The <tt><em>collection</em>.find</tt> method finds objects within the collection :conditions => ["created_at > ?", 2.days.ago]) </ruby> -h6. <em>collection</em>.exist?(...) +h6. <tt><em>collection</em>.exist?(...)</tt> 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 +ActiveRecord::Base.exists?+. -h6. <em>collection</em>.build(attributes = {}) +h6. <tt><em>collection</em>.build(attributes = {})</tt> 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 _not_ yet be saved. @@ -1485,7 +1484,7 @@ The <tt><em>collection</em>.build</tt> method returns a new object of the associ {:assembly_name => "Transmission housing"}) </ruby> -h6. <em>collection</em>.create(attributes = {}) +h6. <tt><em>collection</em>.create(attributes = {})</tt> 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 the join table will be created, and the associated object _will_ be saved (assuming that it passes any validations). @@ -1494,7 +1493,7 @@ The <tt><em>collection</em>.create</tt> method returns a new object of the assoc {:assembly_name => "Transmission housing"}) </ruby> -h5. Options for has_and_belongs_to_many +h5. Options for +has_and_belongs_to_many+ In many situations, you can use the default behavior for +has_and_belongs_to_many+ 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 +has_and_belongs_to_many+ association. For example, an association with several options might look like this: @@ -1528,7 +1527,7 @@ The +has_and_belongs_to_many+ association supports these options: * +:uniq+ * +:validate+ -h6. :association_foreign_key +h6. +:association_foreign_key+ 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 +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly: @@ -1542,11 +1541,11 @@ class User < ActiveRecord::Base end </ruby> -h6. :autosave +h6. +:autosave+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. -h6. :class_name +h6. +:class_name+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way: @@ -1556,7 +1555,7 @@ class Parts < ActiveRecord::Base end </ruby> -h6. :conditions +h6. +:conditions+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). @@ -1576,27 +1575,27 @@ class Parts < ActiveRecord::Base end </ruby> -If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the factory column has the value "Seattle". +If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the +factory+ column has the value "Seattle". -h6. :counter_sql +h6. +:counter_sql+ Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself. NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement. -h6. :delete_sql +h6. +:delete_sql+ Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself. -h6. :extend +h6. +:extend+ -The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>. +The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#associationextensions">later in this guide</a>. -h6. :finder_sql +h6. +:finder_sql+ Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary. -h6. :foreign_key +h6. +:foreign_key+ 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 +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly: @@ -1608,7 +1607,7 @@ class User < ActiveRecord::Base end </ruby> -h6. :group +h6. +:group+ The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL. @@ -1618,19 +1617,19 @@ class Parts < ActiveRecord::Base end </ruby> -h6. :include +h6. +:include+ You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. -h6. :insert_sql +h6. +:insert_sql+ Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself. -h6. :join_table +h6. +:join_table+ If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default. -h6. :limit +h6. +:limit+ The +:limit+ option lets you restrict the total number of objects that will be fetched through an association. @@ -1641,11 +1640,11 @@ class Parts < ActiveRecord::Base end </ruby> -h6. :offset +h6. +:offset+ The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. -h6. :order +h6. +:order+ The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). @@ -1655,23 +1654,23 @@ class Parts < ActiveRecord::Base end </ruby> -h6. :readonly +h6. +:readonly+ If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association. -h6. :select +h6. +:select+ The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns. -h6. :uniq +h6. +:uniq+ Specify the +:uniq => true+ option to remove duplicates from the collection. -h6. :validate +h6. +:validate+ If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved. -h5. When are Objects Saved? +h5. When are objects saved? When you assign an object to a +has_and_belongs_to_many+ 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. @@ -1681,7 +1680,7 @@ If the parent object (the one declaring the +has_and_belongs_to_many+ associatio If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method. -h4. Association Callbacks +h4. Association callbacks 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 +:before_save+ callback to cause something to happen just before an object is saved. @@ -1725,7 +1724,7 @@ end If a +before_add+ callback throws an exception, the object does not get added to the collection. Similarly, if a +before_remove+ callback throws an exception, the object does not get removed from the collection. -h4. Association Extensions +h4. Association extensions 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: @@ -1757,7 +1756,7 @@ class Supplier < ActiveRecord::Base end </ruby> -To include more than one extension module in a single association, specify an array of names: +To include more than one extension module in a single association, specify an array of modules: <ruby> class Customer < ActiveRecord::Base |