aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/activerecord/association_basics.txt
diff options
context:
space:
mode:
Diffstat (limited to 'railties/doc/guides/activerecord/association_basics.txt')
-rw-r--r--railties/doc/guides/activerecord/association_basics.txt604
1 files changed, 392 insertions, 212 deletions
diff --git a/railties/doc/guides/activerecord/association_basics.txt b/railties/doc/guides/activerecord/association_basics.txt
index 9d950c91dd..f9ec7a5f55 100644
--- a/railties/doc/guides/activerecord/association_basics.txt
+++ b/railties/doc/guides/activerecord/association_basics.txt
@@ -9,7 +9,7 @@ This guide covers the association features of Active Record. By referring to thi
== Why Associations?
-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 customers model and an orders model. Each customer can have many orders. Without associations, the model declarations would look like this:
+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:
[source, ruby]
-------------------------------------------------------
@@ -52,12 +52,13 @@ end
-------------------------------------------------------
With this change, creating a new order for a particular customer is easier:
+
[source, ruby]
-------------------------------------------------------
@order = @customer.orders.create(:order_date => Time.now)
-------------------------------------------------------
-Deleting a customer and all of its orders is much easier:
+Deleting a customer and all of its orders is _much_ easier:
[source, ruby]
-------------------------------------------------------
@@ -68,7 +69,7 @@ To learn more about the different types of associations, read the next section o
== The Types of Associations
-In Rails, an _association_ 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 +belongs_to+ another, you enable 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:
+In Rails, an _association_ 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 +belongs_to+ 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:
* +belongs_to+
* +has_one+
@@ -90,6 +91,8 @@ class Order < ActiveRecord::Base
end
-------------------------------------------------------
+image:images/belongs_to.png[belongs_to Association Diagram]
+
=== 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:
@@ -101,18 +104,23 @@ class Supplier < ActiveRecord::Base
end
-------------------------------------------------------
+image:images/has_one.png[has_one Association Diagram]
+
=== 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:
+
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :customers
+ has_many :orders
end
-------------------------------------------------------
NOTE: The name of the other model is pluralized when declaring a +has_many+ association.
+image:images/has_many.png[has_many Association Diagram]
+
=== 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:
@@ -132,6 +140,28 @@ end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
+end
+-------------------------------------------------------
+
+image:images/has_many_through.png[has_many :through Association Diagram]
+
+The +has_many :through+ association is also useful for setting up "shortcuts" through nested :+has_many+ 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:
+
+[source, ruby]
+-------------------------------------------------------
+class Document < ActiveRecord::Base
+ has_many :sections
+ has_many :paragraphs, :through => :sections
+end
+
+class Section < ActiveRecord::Base
+ belongs_to :document
+ has_many :paragraphs
+end
+
+class Paragraph < ActiveRecord::Base
+ belongs_to :section
+end
-------------------------------------------------------
=== The +has_one :through+ Association
@@ -146,7 +176,7 @@ class Supplier < ActiveRecord::Base
end
class Account < ActiveRecord::Base
- belongs_to :account
+ belongs_to :supplier
has_one :account_history
end
@@ -155,6 +185,8 @@ class AccountHistory < ActiveRecord::Base
end
-------------------------------------------------------
+image:images/has_one_through.png[has_one :through Association Diagram]
+
=== 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:
@@ -170,6 +202,8 @@ class Part < ActiveRecord::Base
end
-------------------------------------------------------
+image:images/habtm.png[has_and_belongs_to_many Association Diagram]
+
=== 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?
@@ -212,6 +246,8 @@ class CreateSuppliers < ActiveRecord::Migration
end
-------------------------------------------------------
+NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and implicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead.
+
=== 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:
@@ -262,15 +298,15 @@ class Picture < ActiveRecord::Base
end
class Employee < ActiveRecord::Base
- has_many :pictures, :as => :attachable
+ has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
- has_many :pictures, :as => :attachable
+ has_many :pictures, :as => :imageable
end
-------------------------------------------------------
-You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. 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:
+You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+. Similarly, you can retrieve +@product.pictures+. If you have an instance of the +Picture+ model, you can get to its parent via +@picture.imageable+. 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:
[source, ruby]
-------------------------------------------------------
@@ -290,6 +326,41 @@ class CreatePictures < ActiveRecord::Migration
end
-------------------------------------------------------
+This migration can be simplified by using the +t.references+ form:
+
+[source, ruby]
+-------------------------------------------------------
+class CreatePictures < ActiveRecord::Migration
+ def self.up
+ create_table :pictures do |t|
+ t.string :name
+ t.references :imageable, :polymorphic => true
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :pictures
+ end
+end
+-------------------------------------------------------
+
+image:images/polymorphic.png[Polymorphic Association Diagram]
+
+=== 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 manager and subordinates. This situation can be modeled with self-joining associations:
+
+[source, ruby]
+-------------------------------------------------------
+class Employee < ActiveRecord::Base
+ has_many :subordinates, :class_name => :user, :foreign_key => "manager_id"
+ belongs_to :manager, :class_name => :user
+end
+-------------------------------------------------------
+
+With this setup, you can retrieve +@employee.subordinates+ and +@employee.managers+.
+
== Tips, Tricks, and Warnings
Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
@@ -321,7 +392,7 @@ customer.orders(true).empty? # discards the cached copy of orders and goes ba
=== 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.
+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.
=== Updating the Schema
@@ -355,7 +426,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.
-Second, if you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless name of the join table is explicitly specified by using the +:join_table+ 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.
+Second, 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 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.
WARNING: The precedence between model names is calculated using the +<+ operator for +String+. 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".
@@ -409,9 +480,26 @@ module MyApplication
end
-------------------------------------------------------
-This will work fine, because both the +Supplier+ and the +Account+ class are defined within the same scope.
+This will work fine, because both the +Supplier+ and the +Account+ class are defined within the same scope. But this will not work, because +Supplier+ and +Account+ are defined in different scopes:
+
+[source, ruby]
+-------------------------------------------------------
+module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account
+ end
+ end
+
+ module Billing
+ class Account < ActiveRecord::Base
+ belongs_to :supplier
+ end
+ end
+end
+-------------------------------------------------------
-You can associate a model with a model in a different scope, but only by specifying the complete class name in your association declaration:
+To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:
[source, ruby]
-------------------------------------------------------
@@ -528,6 +616,24 @@ class Order < ActiveRecord::Base
end
-------------------------------------------------------
+The +belongs_to+ association supports these options:
+
+// * +:accessible+
+* +:class_name+
+* +:conditions+
+* +:counter_cache+
+* +:dependent+
+* +:foreign_key+
+* +:include+
+* +:polymorphic+
+* +:readonly+
+* +:select+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
===== +: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:
@@ -550,29 +656,6 @@ class Order < ActiveRecord::Base
end
-------------------------------------------------------
-===== +: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.
-
-===== +: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:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id"
-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.
-
-===== +: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.
-
-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.
-
===== +:counter_cache+
The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
@@ -606,7 +689,7 @@ Although the +:counter_cache+ option is specified on the model that includes the
[source, ruby]
-------------------------------------------------------
class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => :customer_count
+ belongs_to :customer, :counter_cache => :count_of_orders
end
class Customer < ActiveRecord::Base
has_many :orders
@@ -615,7 +698,24 @@ end
Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.
-WARNING: When you create a counter cache column in the database, be sure to specify a default value of zero. Otherwise, Rails will not properly maintain the counter.
+===== +: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.
+
+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.
+
+===== +: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:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id"
+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.
===== +:include+
@@ -651,23 +751,26 @@ class Customer < ActiveRecord::Base
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.
+
===== +:polymorphic+
-Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
+Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
===== +:readonly+
If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
-===== +:validate+
+===== +:select+
-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.
+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.
-===== +:accessible+
+===== +:validate+
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
+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.
==== 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.
=== The has_one Association
@@ -693,7 +796,7 @@ class Supplier < ActiveRecord::Base
end
-------------------------------------------------------
-Each instance of the order model will have these methods:
+Each instance of the +Supplier+ model will have these methods:
[source, ruby]
-------------------------------------------------------
@@ -737,7 +840,7 @@ end
===== +build___association__(attributes = {})+
-The +build__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this its foreign key will be set, but the associated object will _not_ yet be saved.
+The +build__\_association__+ 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.
[source, ruby]
-------------------------------------------------------
@@ -755,7 +858,6 @@ The +create__\_association__+ method returns a new object of the associated type
==== 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:
[source, ruby]
@@ -765,6 +867,32 @@ class Supplier < ActiveRecord::Base
end
-------------------------------------------------------
+The +has_one+ association supports these options:
+
+// * +:accessible+
+* +:as+
+* +:class_name+
+* +:conditions+
+* +:dependent+
+* +:foreign_key+
+* +:include+
+* +:order+
+* +:primary_key+
+* +:readonly+
+* +:select+
+* +:source+
+* +:source_type+
+* +:through+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:as+
+
+Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
+
===== +: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:
@@ -787,10 +915,6 @@ class Supplier < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +WHERE+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
-
===== +: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+.
@@ -808,10 +932,6 @@ 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.
-===== +: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.
-
===== +: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:
@@ -846,17 +966,21 @@ class Representative < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:as+
+===== +:order+
-Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
+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.
-===== +:select+
+===== +:primary_key+
-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.
+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.
-===== +:through+
+===== +:readonly+
-The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide.
+If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
+
+===== +: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.
===== +:source+
@@ -866,18 +990,14 @@ The +:source+ option specifies the source association name for a +has_one :throu
The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
-===== +:readonly+
+===== +:through+
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
+The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide.
===== +: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.
-===== +:accessible+
-
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
-
==== 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.
@@ -923,19 +1043,19 @@ Each instance of the customer model will have these methods:
[source, ruby]
-------------------------------------------------------
-+orders(force_reload = false)+
-+orders<<(object, ...)+
-+orders.delete(object, ...)+
-+orders=objects+
-+order_ids+
-+order_ids=ids+
-+orders.clear+
-+orders.empty?+
-+orders.size+
-+orders.find(...)+
-+orders.exist?(...)+
-+orders.build(attributes = {}, ...)+
-+orders.create(attributes = {})+
+orders(force_reload = false)
+orders<<(object, ...)
+orders.delete(object, ...)
+orders=objects
+order_ids
+order_ids=ids
+orders.clear
+orders.empty?
+orders.size
+orders.find(...)
+orders.exist?(...)
+orders.build(attributes = {}, ...)
+orders.create(attributes = {})
-------------------------------------------------------
===== +_collection_(force_reload = false)+
@@ -949,7 +1069,7 @@ The +_collection_+ method returns an array of all of the associated objects. If
===== +_collection_<<(object, ...)+
-The +_collection<<+ method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
+The +_collection_<<+ method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
[source, ruby]
-------------------------------------------------------
@@ -973,8 +1093,6 @@ The +_collection_=+ method makes the collection contain only the supplied object
===== +_collection\_singular_\_ids+
-# Returns an array of the associated objects' ids
-
The +_collection\_singular_\_ids+ method returns an array of the ids of the objects in the collection.
[source, ruby]
@@ -1034,7 +1152,7 @@ The +_collection_.build+ method returns one or more new objects of the associate
===== +_collection_.create(attributes = {})+
-The +_collection_.create+ method returns one 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).
+The +_collection_.create+ 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).
[source, ruby]
-------------------------------------------------------
@@ -1043,7 +1161,7 @@ The +_collection_.create+ method returns one a new object of the associated type
==== 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 cover the options that you can pass when you create a +has_many+ association. For example, an association with several options might look like this:
+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:
[source, ruby]
-------------------------------------------------------
@@ -1052,6 +1170,39 @@ class Customer < ActiveRecord::Base
end
-------------------------------------------------------
+The +has_many+ association supports these options:
+
+// * +:accessible+
+* +:as+
+* +:class_name+
+* +:conditions+
+* +:counter_sql+
+* +:dependent+
+* +:extend+
+* +:finder_sql+
+* +:foreign_key+
+* +:group+
+* +:include+
+* +:limit+
+* +:offset+
+* +:order+
+* +:primary_key+
+* +:readonly+
+* +:select+
+* +:source+
+* +:source_type+
+* +:through+
+* +:uniq+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:as+
+
+Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
+
===== +: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 transactions, you'd set things up this way:
@@ -1085,16 +1236,25 @@ 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+.
-===== +:order+
+===== +:counter_sql+
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +WHERE+ clause).
+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.
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :order => "date_confirmed DESC"
-end
--------------------------------------------------------
+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.
+
+===== +: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+.
+
+NOTE: This option is ignored when you use the +:through+ option on the association.
+
+===== +:extend+
+
+The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+
+===== +: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.
===== +:foreign_key+
@@ -1109,29 +1269,16 @@ 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.
-===== +: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.
-
-===== +: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+, 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.
-
-===== +: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.
-
-===== +: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.
+===== +:group+
-===== +:extend+
+The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :line_items, :through => :orders, :group => "orders.id"
+end
+-------------------------------------------------------
===== +:include+
@@ -1147,7 +1294,7 @@ class Order < ActiveRecord::Base
has_many :line_items
end
class LineItem < ActiveRecord::Base
- belongs_to :orders
+ belongs_to :order
end
-------------------------------------------------------
@@ -1163,35 +1310,43 @@ class Order < ActiveRecord::Base
has_many :line_items
end
class LineItem < ActiveRecord::Base
- belongs_to :orders
+ belongs_to :order
end
-------------------------------------------------------
-===== +:group+
+===== +:limit+
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
+The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :line_items, :through => :orders, :group => "orders.id"
+ has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100
end
-------------------------------------------------------
-===== +:limit+
+===== +:offset+
-The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
+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 10 records.
+
+===== +:order+
+
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100
+ has_many :orders, :order => "date_confirmed DESC"
end
-------------------------------------------------------
-===== +:offset+
+===== +:primary_key+
-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 10 records.
+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.
+
+===== +:readonly+
+
+If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
===== +:select+
@@ -1199,14 +1354,6 @@ The +:select+ option lets you override the SQL +SELECT+ clause that is used to r
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.
-===== +:as+
-
-Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
-
-===== +: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 earlier in this guide.
-
===== +: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.
@@ -1215,22 +1362,18 @@ The +:source+ option specifies the source association name for a +has_many :thro
The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
-===== +:uniq+
+===== +:through+
-Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
+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 earlier in this guide.
-===== +:readonly+
+===== +:uniq+
-If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
+Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
===== +: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.
-===== +:accessible+
-
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
-
==== 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.
@@ -1263,11 +1406,11 @@ When you declare a +has_and_belongs_to_many+ association, the declaring class au
* +_collection_.build(attributes = {})+
* +_collection_.create(attributes = {})+
-In all of these methods, +_collection_+ is replaced with the symbol passed as the first argument to +has_many+, and +_collection\_singular+ is replaced with the singularized version of that symbol.. For example, given the declaration:
+In all of these methods, +_collection_+ is replaced with the symbol passed as the first argument to +has_many+, and +_collection_\_singular+ is replaced with the singularized version of that symbol.. For example, given the declaration:
[source, ruby]
-------------------------------------------------------
-class Parts < ActiveRecord::Base
+class Part < ActiveRecord::Base
has_and_belongs_to_many :assemblies
end
-------------------------------------------------------
@@ -1276,24 +1419,24 @@ Each instance of the part model will have these methods:
[source, ruby]
-------------------------------------------------------
-+assemblies(force_reload = false)+
-+assemblies<<(object, ...)+
-+assemblies.delete(object, ...)+
-+assemblies=objects+
-+assembly_ids+
-+assembly_ids=ids+
-+assemblies.clear+
-+assemblies.empty?+
-+assemblies.size+
-+assemblies.find(...)+
-+assemblies.exist?(...)+
-+assemblies.build(attributes = {}, ...)+
-+assemblies.create(attributes = {})+
+assemblies(force_reload = false)
+assemblies<<(object, ...)
+assemblies.delete(object, ...)
+assemblies=objects
+assembly_ids
+assembly_ids=ids
+assemblies.clear
+assemblies.empty?
+assemblies.size
+assemblies.find(...)
+assemblies.exist?(...)
+assemblies.build(attributes = {}, ...)
+assemblies.create(attributes = {})
-------------------------------------------------------
-===== Additional Field Methods
+===== Additional Column Methods
-If the join table for a +has_and_belongs_to_many+ association has additional fields beyond the two foreign keys, these fields 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.
+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+.
@@ -1309,7 +1452,7 @@ The +_collection_+ method returns an array of all of the associated objects. If
===== +_collection_<<(object, ...)+
-The +_collection<<+ method adds one or more objects to the collection by creating records in the join table.
+The +_collection_<<+ method adds one or more objects to the collection by creating records in the join table.
[source, ruby]
-------------------------------------------------------
@@ -1320,7 +1463,7 @@ NOTE: This method is aliased as +_collection_.concat+ and +_collection_.push+.
===== +_collection_.delete(object, ...)+
-The +_collection_.delete+ method removes one or more objects from the collection by deleting records in the join table+. This does not destroy the objects.
+The +_collection_.delete+ method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
[source, ruby]
-------------------------------------------------------
@@ -1348,7 +1491,7 @@ The +_collection\_singular_\_ids=+ method makes the collection contain only the
===== +_collection_.clear+
-The +_collection_.clear+ method removes every object from the collection. This does not destroy the associated objects.
+The +_collection_.clear+ method removes every object from the collection by deleting the rows from the joining tableassociation. This does not destroy the associated objects.
===== +_collection_.empty?+
@@ -1412,25 +1555,33 @@ class Parts < ActiveRecord::Base
end
-------------------------------------------------------
-===== +: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 gadgets, you'd set things up this way:
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :class_name => :gadgets
-end
--------------------------------------------------------
-
-===== +: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.
-
-===== +: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:
-
+The +has_and_belongs_to_many+ association supports these options:
+
+// * +:accessible+
+* +:association_foreign_key+
+* +:class_name+
+* +:conditions+
+* +:counter_sql+
+* +:delete_sql+
+* +:extend+
+* +:finder_sql+
+* +:foreign_key+
+* +:group+
+* +:include+
+* +:insert_sql+
+* +:join_table+
+* +:limit+
+* +:offset+
+* +:order+
+* +:readonly+
+* +:select+
+* +:uniq+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
===== +: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:
@@ -1445,47 +1596,38 @@ class User < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:conditions+
+===== +:class_name+
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+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 gadgets, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
+ has_and_belongs_to_many :assemblies, :class_name => :gadgets
end
-------------------------------------------------------
-You can also set conditions via a hash:
+===== +:conditions+
+
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
+ has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
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 +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the factory column has the value "Seattle".
-
-===== +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +WHERE+ clause).
-
+You can also set conditions via a hash:
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
+ has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
end
-------------------------------------------------------
-===== +:uniq+
-
-Specify the +:uniq => true+ option to remove duplicates from the collection.
-
-===== +: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.
+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".
===== +:counter_sql+
@@ -1497,17 +1639,25 @@ NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter 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.
-===== +: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.
-
===== +:extend+
The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
-===== +:include+
+===== +:finder_sql+
-You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+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.
+
+===== +: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:
+
+[source, ruby]
+-------------------------------------------------------
+class User < ActiveRecord::Base
+ has_and_belongs_to_many :friends, :class_name => :users,
+ :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
+end
+-------------------------------------------------------
===== +:group+
@@ -1520,6 +1670,18 @@ class Parts < ActiveRecord::Base
end
-------------------------------------------------------
+===== +:include+
+
+You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+
+===== +: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.
+
+===== +: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.
+
===== +:limit+
The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
@@ -1535,22 +1697,32 @@ end
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 10 records.
-===== +:select+
+===== +:order+
-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.
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
+end
+-------------------------------------------------------
===== +:readonly+
If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
-===== +:validate+
+===== +:select+
-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.
+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.
-===== +:accessible+
+===== +:uniq+
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
+Specify the +:uniq => true+ option to remove duplicates from the collection.
+===== +: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.
==== When are Objects Saved?
@@ -1568,10 +1740,10 @@ Normal callbacks hook into the lifecycle of Active Record objects, allowing you
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:
-* before_add
-* after_add
-* before_remove
-* after_remove
+* +before_add+
+* +after_add+
+* +before_remove+
+* +after_remove+
You define association callbacks by adding options to the association declaration. For example:
@@ -1655,3 +1827,11 @@ Extensions can refer to the internals of the association proxy using these three
* +proxy_owner+ returns the object that the association is a part of.
* +proxy_reflection+ returns the reflection object that describes the association.
* +proxy_target+ returns the associated object for +belongs_to+ or +has_one+, or the collection of associated objects for +has_many+ or +has_and_belongs_to_many+.
+
+== Changelog ==
+
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11[Lighthouse ticket]
+
+* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
+* September 22, 2008: Added diagrams, misc. cleanup by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)