1 A Guide to Active Record Associations
2 =====================================
4 This guide covers the association features of Active Record. By referring to this guide, you will be able to:
6 * Declare associations between Active Record models
7 * Understand the various types of Active Record associations
8 * Use the methods added to your models by creating associations
12 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:
15 -------------------------------------------------------
16 class Customer < ActiveRecord::Base
19 class Order < ActiveRecord::Base
21 -------------------------------------------------------
23 Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
26 -------------------------------------------------------
27 @order = Order.create(:order_date => Time.now, :customer_id => @customer.id)
28 -------------------------------------------------------
30 Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
33 -------------------------------------------------------
34 @orders = Order.find_by_customer_id(@customer.id)
35 @orders.each do |order|
39 -------------------------------------------------------
41 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:
44 -------------------------------------------------------
45 class Customer < ActiveRecord::Base
49 class Order < ActiveRecord::Base
52 -------------------------------------------------------
54 With this change, creating a new order for a particular customer is easier:
57 -------------------------------------------------------
58 @order = @customer.orders.create(:order_date => Time.now)
59 -------------------------------------------------------
61 Deleting a customer and all of its orders is _much_ easier:
64 -------------------------------------------------------
66 -------------------------------------------------------
68 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.
70 == The Types of Associations
72 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:
79 * +has_and_belongs_to_many+
81 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.
83 === The +belongs_to+ Association
85 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 -------------------------------------------------------
89 class Order < ActiveRecord::Base
92 -------------------------------------------------------
94 image:images/belongs_to.png[belongs_to Association Diagram]
96 === The +has_one+ Association
98 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 -------------------------------------------------------
102 class Supplier < ActiveRecord::Base
105 -------------------------------------------------------
107 image:images/has_one.png[has_one Association Diagram]
109 === The +has_many+ Association
111 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 -------------------------------------------------------
115 class Customer < ActiveRecord::Base
118 -------------------------------------------------------
120 NOTE: The name of the other model is pluralized when declaring a +has_many+ association.
122 image:images/has_many.png[has_many Association Diagram]
124 === The +has_many :through+ Association
126 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:
129 -------------------------------------------------------
130 class Physician < ActiveRecord::Base
131 has_many :appointments
132 has_many :patients, :through => :appointments
135 class Appointment < ActiveRecord::Base
136 belongs_to :physician
140 class Patient < ActiveRecord::Base
141 has_many :appointments
142 has_many :physicians, :through => :appointments
144 -------------------------------------------------------
146 image:images/has_many_through.png[has_many :through Association Diagram]
148 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:
151 -------------------------------------------------------
152 class Document < ActiveRecord::Base
154 has_many :paragraphs, :through => :sections
157 class Section < ActiveRecord::Base
162 class Paragraph < ActiveRecord::Base
165 -------------------------------------------------------
167 === The +has_one :through+ Association
169 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:
172 -------------------------------------------------------
173 class Supplier < ActiveRecord::Base
175 has_one :account_history, :through => :account
178 class Account < ActiveRecord::Base
180 has_one :account_history
183 class AccountHistory < ActiveRecord::Base
186 -------------------------------------------------------
188 image:images/has_one_through.png[has_one :through Association Diagram]
190 === The +has_and_belongs_to_many+ Association
192 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:
195 -------------------------------------------------------
196 class Assembly < ActiveRecord::Base
197 has_and_belongs_to_many :parts
200 class Part < ActiveRecord::Base
201 has_and_belongs_to_many :assemblies
203 -------------------------------------------------------
205 image:images/habtm.png[has_and_belongs_to_many Association Diagram]
207 === Choosing Between +belongs_to+ and +has_one+
209 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?
211 The distinction is in where you place the foreign key (it goes on the table for the class declaring the +belongs_to+ association), but you should give some thought to the actual meaning of the data as well. The +has_one+ relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
214 -------------------------------------------------------
215 class Supplier < ActiveRecord::Base
219 class Account < ActiveRecord::Base
222 -------------------------------------------------------
224 The corresponding migration might look like this:
227 -------------------------------------------------------
228 class CreateSuppliers < ActiveRecord::Migration
230 create_table :suppliers do |t|
235 create_table :accounts do |t|
236 t.integer :supplier_id
237 t.string :account_number
244 drop_table :suppliers
247 -------------------------------------------------------
249 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.
251 === Choosing Between +has_many :through+ and +has_and_belongs_to_many+
253 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:
256 -------------------------------------------------------
257 class Assembly < ActiveRecord::Base
258 has_and_belongs_to_many :parts
261 class Part < ActiveRecord::Base
262 has_and_belongs_to_many :assemblies
264 -------------------------------------------------------
266 The second way to declare a many-to-many relationship is to use +has_many :through+. This makes the association indirectly, through a join model:
269 -------------------------------------------------------
270 class Assembly < ActiveRecord::Base
272 has_many :parts, :through => :manifests
275 class Manifest < ActiveRecord::Base
280 class Part < ActiveRecord::Base
282 has_many :assemblies, :through => :manifests
284 -------------------------------------------------------
286 The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table).
288 You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.
290 === Polymorphic Associations
292 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:
295 -------------------------------------------------------
296 class Picture < ActiveRecord::Base
297 belongs_to :imageable, :polymorphic => true
300 class Employee < ActiveRecord::Base
301 has_many :pictures, :as => :imageable
304 class Product < ActiveRecord::Base
305 has_many :pictures, :as => :imageable
307 -------------------------------------------------------
309 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:
312 -------------------------------------------------------
313 class CreatePictures < ActiveRecord::Migration
315 create_table :pictures do |t|
317 t.integer :imageable_id
318 t.string :imageable_type
327 -------------------------------------------------------
329 This migration can be simplified by using the +t.references+ form:
332 -------------------------------------------------------
333 class CreatePictures < ActiveRecord::Migration
335 create_table :pictures do |t|
337 t.references :imageable, :polymorphic => true
346 -------------------------------------------------------
348 image:images/polymorphic.png[Polymorphic Association Diagram]
352 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:
355 -------------------------------------------------------
356 class Employee < ActiveRecord::Base
357 has_many :subordinates, :class_name => "User", :foreign_key => "manager_id"
358 belongs_to :manager, :class_name => "User"
360 -------------------------------------------------------
362 With this setup, you can retrieve +@employee.subordinates+ and +@employee.manager+.
364 == Tips, Tricks, and Warnings
366 Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
368 * Controlling caching
369 * Avoiding name collisions
370 * Updating the schema
371 * Controlling association scope
373 === Controlling Caching
375 All of the association methods are built around caching that keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
378 -------------------------------------------------------
379 customer.orders # retrieves orders from the database
380 customer.orders.size # uses the cached copy of orders
381 customer.orders.empty? # uses the cached copy of orders
382 -------------------------------------------------------
384 But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass +true+ to the association call:
387 -------------------------------------------------------
388 customer.orders # retrieves orders from the database
389 customer.orders.size # uses the cached copy of orders
390 customer.orders(true).empty? # discards the cached copy of orders and goes back to the database
391 -------------------------------------------------------
393 === Avoiding Name Collisions
395 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.
397 === Updating the Schema
399 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. First, you need to create foreign keys as appropriate:
402 -------------------------------------------------------
403 class Order < ActiveRecord::Base
406 -------------------------------------------------------
408 This declaration needs to be backed up by the proper foreign key declaration on the orders table:
411 -------------------------------------------------------
412 class CreateOrders < ActiveRecord::Migration
414 create_table :orders do |t|
415 t.order_date :datetime
416 t.order_number :string
417 t.customer_id :integer
425 -------------------------------------------------------
427 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.
429 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.
431 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".
433 Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
436 -------------------------------------------------------
437 class Assembly < ActiveRecord::Base
438 has_and_belongs_to_many :parts
441 class Part < ActiveRecord::Base
442 has_and_belongs_to_many :assemblies
444 -------------------------------------------------------
446 These need to be backed up by a migration to create the +assemblies_parts+ table. This table should be created without a primary key:
449 -------------------------------------------------------
450 class CreateAssemblyPartJoinTable < ActiveRecord::Migration
452 create_table :assemblies_parts, :id => false do |t|
453 t.integer :assembly_id
459 drop_table :assemblies_parts
462 -------------------------------------------------------
464 === Controlling Association Scope
466 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:
469 -------------------------------------------------------
472 class Supplier < ActiveRecord::Base
476 class Account < ActiveRecord::Base
481 -------------------------------------------------------
483 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:
486 -------------------------------------------------------
489 class Supplier < ActiveRecord::Base
495 class Account < ActiveRecord::Base
500 -------------------------------------------------------
502 To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:
505 -------------------------------------------------------
508 class Supplier < ActiveRecord::Base
509 has_one :account, :class_name => "MyApplication::Billing::Account"
514 class Account < ActiveRecord::Base
515 belongs_to :supplier, :class_name => "MyApplication::Business::Supplier"
519 -------------------------------------------------------
521 == Detailed Association Reference
523 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.
525 === The +belongs_to+ Association
527 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.
529 ==== Methods Added by +belongs_to+
531 When you declare a +belongs_to+ assocation, the declaring class automatically gains five methods related to the association:
533 * +_association_(force_reload = false)+
534 * +_association_=(associate)+
535 * +_association_.nil?+
536 * +build___association__(attributes = {})+
537 * +create___association__(attributes = {})+
539 In all of these methods, +_association_+ is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration:
542 -------------------------------------------------------
543 class Order < ActiveRecord::Base
546 -------------------------------------------------------
548 Each instance of the order model will have these methods:
551 -------------------------------------------------------
557 -------------------------------------------------------
559 ===== +_association_(force_reload = false)+
561 The +_association_+ method returns the associated object, if any. If no associated object is found, it returns +nil+.
564 -------------------------------------------------------
565 @customer = @order.customer
566 -------------------------------------------------------
568 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.
570 ===== +_association_=(associate)+
572 The +_association_=+ method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
575 -------------------------------------------------------
576 @order.customer = @customer
577 -------------------------------------------------------
579 ===== +_association_.nil?+
581 The +_association_.nil?+ method returns +true+ if there is no associated object.
584 -------------------------------------------------------
585 if @order.customer.nil?
586 @msg = "No customer found for this order"
588 -------------------------------------------------------
590 ===== +build___association__(attributes = {})+
592 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 object's foreign key will be set, but the associated object will _not_ yet be saved.
595 -------------------------------------------------------
596 @customer = @order.build_customer({:customer_number => 123, :customer_name => "John Doe"})
597 -------------------------------------------------------
599 ===== +create___association__(attributes = {})+
601 The +create__\_association__+ 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).
604 -------------------------------------------------------
605 @customer = @order.create_customer({:customer_number => 123, :customer_name => "John Doe"})
606 -------------------------------------------------------
608 ==== Options for +belongs_to+
610 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:
613 -------------------------------------------------------
614 class Order < ActiveRecord::Base
615 belongs_to :customer, :counter_cache => true, :conditions => "active = 1"
617 -------------------------------------------------------
619 The +belongs_to+ association supports these options:
633 // ===== +:accessible+
635 // 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.
639 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:
642 -------------------------------------------------------
643 class Order < ActiveRecord::Base
644 belongs_to :customer, :class_name => "Patron"
646 -------------------------------------------------------
650 The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
653 -------------------------------------------------------
654 class Order < ActiveRecord::Base
655 belongs_to :customer, :conditions => "active = 1"
657 -------------------------------------------------------
659 ===== +:counter_cache+
661 The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
664 -------------------------------------------------------
665 class Order < ActiveRecord::Base
668 class Customer < ActiveRecord::Base
671 -------------------------------------------------------
673 With these declarations, asking for the value of +@customer.orders.size+ requires making a call to the database to perform a +COUNT(*)+ query. To avoid this call, you can add a counter cache to the _belonging_ model:
676 -------------------------------------------------------
677 class Order < ActiveRecord::Base
678 belongs_to :customer, :counter_cache => true
680 class Customer < ActiveRecord::Base
683 -------------------------------------------------------
685 With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +.size+ method.
687 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:
690 -------------------------------------------------------
691 class Order < ActiveRecord::Base
692 belongs_to :customer, :counter_cache => :count_of_orders
694 class Customer < ActiveRecord::Base
697 -------------------------------------------------------
699 Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.
703 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.
705 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.
709 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:
712 -------------------------------------------------------
713 class Order < ActiveRecord::Base
714 belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id"
716 -------------------------------------------------------
718 TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
722 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:
725 -------------------------------------------------------
726 class LineItem < ActiveRecord::Base
729 class Order < ActiveRecord::Base
733 class Customer < ActiveRecord::Base
736 -------------------------------------------------------
738 If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
741 -------------------------------------------------------
742 class LineItem < ActiveRecord::Base
743 belongs_to :order, :include => :customer
745 class Order < ActiveRecord::Base
749 class Customer < ActiveRecord::Base
752 -------------------------------------------------------
754 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.
758 Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
762 If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
766 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.
768 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.
772 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.
774 ==== When are Objects Saved?
776 Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
778 === The has_one Association
780 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.
782 ==== Methods Added by +has_one+
784 When you declare a +has_one+ association, the declaring class automatically gains five methods related to the association:
786 * +_association_(force_reload = false)+
787 * +_association_=(associate)+
788 * +_association_.nil?+
789 * +build___association__(attributes = {})+
790 * +create___association__(attributes = {})+
792 In all of these methods, +_association_+ is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration:
795 -------------------------------------------------------
796 class Supplier < ActiveRecord::Base
799 -------------------------------------------------------
801 Each instance of the +Supplier+ model will have these methods:
804 -------------------------------------------------------
810 -------------------------------------------------------
812 ===== +_association_(force_reload = false)+
814 The +_association_+ method returns the associated object, if any. If no associated object is found, it returns +nil+.
817 -------------------------------------------------------
818 @account = @supplier.account
819 -------------------------------------------------------
821 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.
823 ===== +_association_=(associate)+
825 The +_association_=+ 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.
828 -------------------------------------------------------
829 @suppler.account = @account
830 -------------------------------------------------------
832 ===== +_association_.nil?+
834 The +_association_.nil?+ method returns +true+ if there is no associated object.
837 -------------------------------------------------------
838 if @supplier.account.nil?
839 @msg = "No account found for this supplier"
841 -------------------------------------------------------
843 ===== +build___association__(attributes = {})+
845 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.
848 -------------------------------------------------------
849 @account = @supplier.build_account({:terms => "Net 30"})
850 -------------------------------------------------------
852 ===== +create___association__(attributes = {})+
854 The +create__\_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. In addition, the associated object _will_ be saved (assuming that it passes any validations).
857 -------------------------------------------------------
858 @account = @supplier.create_account({:terms => "Net 30"})
859 -------------------------------------------------------
861 ==== Options for +has_one+
863 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:
866 -------------------------------------------------------
867 class Supplier < ActiveRecord::Base
868 has_one :account, :class_name => "Billing", :dependent => :nullify
870 -------------------------------------------------------
872 The +has_one+ association supports these options:
890 // ===== +:accessible+
892 // 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.
896 Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
900 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:
903 -------------------------------------------------------
904 class Supplier < ActiveRecord::Base
905 has_one :account, :class_name => "Billing"
907 -------------------------------------------------------
911 The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
914 -------------------------------------------------------
915 class Supplier < ActiveRecord::Base
916 has_one :account, :conditions => "confirmed = 1"
918 -------------------------------------------------------
922 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+.
926 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:
929 -------------------------------------------------------
930 class Supplier < ActiveRecord::Base
931 has_one :account, :foreign_key => "supp_id"
933 -------------------------------------------------------
935 TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
939 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:
942 -------------------------------------------------------
943 class Supplier < ActiveRecord::Base
946 class Account < ActiveRecord::Base
948 belongs_to :representative
950 class Representative < ActiveRecord::Base
953 -------------------------------------------------------
955 If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
958 -------------------------------------------------------
959 class Supplier < ActiveRecord::Base
960 has_one :account, :include => :representative
962 class Account < ActiveRecord::Base
964 belongs_to :representative
966 class Representative < ActiveRecord::Base
969 -------------------------------------------------------
973 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.
977 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.
981 If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
985 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.
989 The +:source+ option specifies the source association name for a +has_one :through+ association.
993 The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
997 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.
1001 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.
1003 ==== When are Objects Saved?
1005 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.
1007 If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1009 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.
1011 If you want to assign an object to a +has_one+ association without saving the object, use the +association.build+ method.
1013 === The has_many Association
1015 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.
1019 When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:
1021 * +_collection_(force_reload = false)+
1022 * +_collection_<<(object, ...)+
1023 * +_collection_.delete(object, ...)+
1024 * +_collection_=objects+
1025 * +_collection\_singular_\_ids+
1026 * +_collection\_singular_\_ids=ids+
1027 * +_collection_.clear+
1028 * +_collection_.empty?+
1029 * +_collection_.size+
1030 * +_collection_.find(...)+
1031 * +_collection_.exist?(...)+
1032 * +_collection_.build(attributes = {}, ...)+
1033 * +_collection_.create(attributes = {})+
1035 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:
1038 -------------------------------------------------------
1039 class Customer < ActiveRecord::Base
1042 -------------------------------------------------------
1044 Each instance of the customer model will have these methods:
1047 -------------------------------------------------------
1048 orders(force_reload = false)
1049 orders<<(object, ...)
1050 orders.delete(object, ...)
1059 orders.build(attributes = {}, ...)
1060 orders.create(attributes = {})
1061 -------------------------------------------------------
1063 ===== +_collection_(force_reload = false)+
1065 The +_collection_+ method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
1068 -------------------------------------------------------
1069 @orders = @customer.orders
1070 -------------------------------------------------------
1072 ===== +_collection_<<(object, ...)+
1074 The +_collection_<<+ method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
1077 -------------------------------------------------------
1078 @customer.orders << @order1
1079 -------------------------------------------------------
1081 ===== +_collection_.delete(object, ...)+
1083 The +_collection_.delete+ method removes one or more objects from the collection by setting their foreign keys to +NULL+.
1086 -------------------------------------------------------
1087 @customer.orders.delete(@order1)
1088 -------------------------------------------------------
1090 WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
1093 ===== +_collection_=objects+
1095 The +_collection_=+ method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1097 ===== +_collection\_singular_\_ids+
1099 The +_collection\_singular_\_ids+ method returns an array of the ids of the objects in the collection.
1102 -------------------------------------------------------
1103 @order_ids = @customer.order_ids
1104 -------------------------------------------------------
1106 ===== +__collection\_singular_\_ids=ids+
1108 The +__collection\_singular_\_ids=+ method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
1110 ===== +_collection_.clear+
1112 The +_collection_.clear+ 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+.
1114 ===== +_collection_.empty?+
1116 The +_collection_.empty?+ method returns +true+ if the collection does not contain any associated objects.
1119 -------------------------------------------------------
1120 <% if @customer.orders.empty? %>
1123 -------------------------------------------------------
1125 ===== +_collection_.size+
1127 The +_collection_.size+ method returns the number of objects in the collection.
1130 -------------------------------------------------------
1131 @order_count = @customer.orders.size
1132 -------------------------------------------------------
1134 ===== +_collection_.find(...)+
1136 The +_collection_.find+ method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
1139 -------------------------------------------------------
1140 @open_orders = @customer.orders.find(:all, :conditions => "open = 1")
1141 -------------------------------------------------------
1143 ===== +_collection_.exist?(...)+
1145 The +_collection_.exist?+ method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
1147 ===== +_collection_.build(attributes = {}, ...)+
1149 The +_collection_.build+ 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.
1152 -------------------------------------------------------
1153 @order = @customer.orders.build({:order_date => Time.now, :order_number => "A12345"})
1154 -------------------------------------------------------
1156 ===== +_collection_.create(attributes = {})+
1158 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).
1161 -------------------------------------------------------
1162 @order = @customer.orders.create({:order_date => Time.now, :order_number => "A12345"})
1163 -------------------------------------------------------
1165 ==== Options for has_many
1167 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:
1170 -------------------------------------------------------
1171 class Customer < ActiveRecord::Base
1172 has_many :orders, :dependent => :delete_all, :validate => :false
1174 -------------------------------------------------------
1176 The +has_many+ association supports these options:
1201 // ===== +:accessible+
1203 // 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.
1207 Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
1211 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:
1214 -------------------------------------------------------
1215 class Customer < ActiveRecord::Base
1216 has_many :orders, :class_name => "Transaction"
1218 -------------------------------------------------------
1222 The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
1225 -------------------------------------------------------
1226 class Customer < ActiveRecord::Base
1227 has_many :confirmed_orders, :class_name => "Order", :conditions => "confirmed = 1"
1229 -------------------------------------------------------
1231 You can also set conditions via a hash:
1234 -------------------------------------------------------
1235 class Customer < ActiveRecord::Base
1236 has_many :confirmed_orders, :class_name => "Order", :conditions => { :confirmed => true }
1238 -------------------------------------------------------
1240 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+.
1242 ===== +:counter_sql+
1244 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.
1246 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.
1250 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+.
1252 NOTE: This option is ignored when you use the +:through+ option on the association.
1256 The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
1260 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.
1262 ===== +:foreign_key+
1264 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:
1267 -------------------------------------------------------
1268 class Customer < ActiveRecord::Base
1269 has_many :orders, :foreign_key => "cust_id"
1271 -------------------------------------------------------
1273 TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
1277 The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1280 -------------------------------------------------------
1281 class Customer < ActiveRecord::Base
1282 has_many :line_items, :through => :orders, :group => "orders.id"
1284 -------------------------------------------------------
1288 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:
1291 -------------------------------------------------------
1292 class Customer < ActiveRecord::Base
1295 class Order < ActiveRecord::Base
1296 belongs_to :customer
1297 has_many :line_items
1299 class LineItem < ActiveRecord::Base
1302 -------------------------------------------------------
1304 If you frequently retrieve line items directly from customers (+@customer.orders.line_items+), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
1307 -------------------------------------------------------
1308 class Customer < ActiveRecord::Base
1309 has_many :orders, :include => :line_items
1311 class Order < ActiveRecord::Base
1312 belongs_to :customer
1313 has_many :line_items
1315 class LineItem < ActiveRecord::Base
1318 -------------------------------------------------------
1322 The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1325 -------------------------------------------------------
1326 class Customer < ActiveRecord::Base
1327 has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100
1329 -------------------------------------------------------
1333 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.
1337 The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
1340 -------------------------------------------------------
1341 class Customer < ActiveRecord::Base
1342 has_many :orders, :order => "date_confirmed DESC"
1344 -------------------------------------------------------
1346 ===== +:primary_key+
1348 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.
1352 If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1356 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.
1358 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.
1362 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.
1364 ===== +:source_type+
1366 The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
1370 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.
1374 Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
1378 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.
1380 ==== When are Objects Saved?
1382 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.
1384 If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1386 If the parent object (the one declaring the +has_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
1388 If you want to assign an object to a +has_many+ association without saving the object, use the +_collection_.build+ method.
1390 === The +has_and_belongs_to_many+ Association
1392 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.
1396 When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:
1398 * +_collection_(force_reload = false)+
1399 * +_collection_<<(object, ...)+
1400 * +_collection_.delete(object, ...)+
1401 * +_collection_=objects+
1402 * +_collection\_singular_\_ids+
1403 * +_collection\_singular_\_ids=ids+
1404 * +_collection_.clear+
1405 * +_collection_.empty?+
1406 * +_collection_.size+
1407 * +_collection_.find(...)+
1408 * +_collection_.exist?(...)+
1409 * +_collection_.build(attributes = {})+
1410 * +_collection_.create(attributes = {})+
1412 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:
1415 -------------------------------------------------------
1416 class Part < ActiveRecord::Base
1417 has_and_belongs_to_many :assemblies
1419 -------------------------------------------------------
1421 Each instance of the part model will have these methods:
1424 -------------------------------------------------------
1425 assemblies(force_reload = false)
1426 assemblies<<(object, ...)
1427 assemblies.delete(object, ...)
1434 assemblies.find(...)
1435 assemblies.exist?(...)
1436 assemblies.build(attributes = {}, ...)
1437 assemblies.create(attributes = {})
1438 -------------------------------------------------------
1440 ===== Additional Column Methods
1442 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.
1444 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+.
1447 ===== +_collection_(force_reload = false)+
1449 The +_collection_+ method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
1452 -------------------------------------------------------
1453 @assemblies = @part.assemblies
1454 -------------------------------------------------------
1456 ===== +_collection_<<(object, ...)+
1458 The +_collection_<<+ method adds one or more objects to the collection by creating records in the join table.
1461 -------------------------------------------------------
1462 @part.assemblies << @assembly1
1463 -------------------------------------------------------
1465 NOTE: This method is aliased as +_collection_.concat+ and +_collection_.push+.
1467 ===== +_collection_.delete(object, ...)+
1469 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.
1472 -------------------------------------------------------
1473 @part.assemblies.delete(@assembly1)
1474 -------------------------------------------------------
1476 ===== +_collection_=objects+
1478 The +_collection_=+ method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1480 ===== +_collection\_singular_\_ids+
1482 # Returns an array of the associated objects' ids
1484 The +_collection\_singular_\_ids+ method returns an array of the ids of the objects in the collection.
1487 -------------------------------------------------------
1488 @assembly_ids = @part.assembly_ids
1489 -------------------------------------------------------
1491 ===== +_collection\_singular_\_ids=ids+
1493 The +_collection\_singular_\_ids=+ method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
1495 ===== +_collection_.clear+
1497 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.
1499 ===== +_collection_.empty?+
1501 The +_collection_.empty?+ method returns +true+ if the collection does not contain any associated objects.
1504 -------------------------------------------------------
1505 <% if @part.assemblies.empty? %>
1506 This part is not used in any assemblies
1508 -------------------------------------------------------
1510 ===== +_collection_.size+
1512 The +_collection_.size+ method returns the number of objects in the collection.
1515 -------------------------------------------------------
1516 @assembly_count = @part.assemblies.size
1517 -------------------------------------------------------
1519 ===== +_collection_.find(...)+
1521 The +_collection_.find+ 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.
1524 -------------------------------------------------------
1525 @new_assemblies = @part.assemblies.find(:all, :conditions => ["created_at > ?", 2.days.ago])
1526 -------------------------------------------------------
1528 ===== +_collection_.exist?(...)+
1530 The +_collection_.exist?+ method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
1532 ===== +_collection_.build(attributes = {})+
1534 The +_collection_.build+ 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.
1537 -------------------------------------------------------
1538 @assembly = @part.assemblies.build({:assembly_name => "Transmission housing"})
1539 -------------------------------------------------------
1541 ===== +_collection_.create(attributes = {})+
1543 The +_collection_.create+ method returns a new object of the associated type. This objects will be instantiated from the passed attributes, the link through the join table will be created, and the associated object _will_ be saved (assuming that it passes any validations).
1546 -------------------------------------------------------
1547 @assembly = @part.assemblies.create({:assembly_name => "Transmission housing"})
1548 -------------------------------------------------------
1550 ==== Options for has_and_belongs_to_many
1552 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 cover 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:
1555 -------------------------------------------------------
1556 class Parts < ActiveRecord::Base
1557 has_and_belongs_to_many :assemblies, :uniq => true, :read_only => true
1559 -------------------------------------------------------
1561 The +has_and_belongs_to_many+ association supports these options:
1564 * +:association_foreign_key+
1584 // ===== +:accessible+
1586 // 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.
1588 ===== +:association_foreign_key+
1590 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:
1592 TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:
1595 -------------------------------------------------------
1596 class User < ActiveRecord::Base
1597 has_and_belongs_to_many :friends, :class_name => "User",
1598 :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
1600 -------------------------------------------------------
1604 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:
1607 -------------------------------------------------------
1608 class Parts < ActiveRecord::Base
1609 has_and_belongs_to_many :assemblies, :class_name => "Gadget"
1611 -------------------------------------------------------
1615 The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
1618 -------------------------------------------------------
1619 class Parts < ActiveRecord::Base
1620 has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
1622 -------------------------------------------------------
1624 You can also set conditions via a hash:
1627 -------------------------------------------------------
1628 class Parts < ActiveRecord::Base
1629 has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
1631 -------------------------------------------------------
1633 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".
1635 ===== +:counter_sql+
1637 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.
1639 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.
1643 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.
1647 The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
1651 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.
1653 ===== +:foreign_key+
1655 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:
1658 -------------------------------------------------------
1659 class User < ActiveRecord::Base
1660 has_and_belongs_to_many :friends, :class_name => "User",
1661 :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
1663 -------------------------------------------------------
1667 The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1670 -------------------------------------------------------
1671 class Parts < ActiveRecord::Base
1672 has_and_belongs_to_many :assemblies, :group => "factory"
1674 -------------------------------------------------------
1678 You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
1682 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.
1686 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.
1690 The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1693 -------------------------------------------------------
1694 class Parts < ActiveRecord::Base
1695 has_and_belongs_to_many :assemblies, :order => "created_at DESC", :limit => 50
1697 -------------------------------------------------------
1701 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.
1705 The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
1708 -------------------------------------------------------
1709 class Parts < ActiveRecord::Base
1710 has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
1712 -------------------------------------------------------
1716 If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1720 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.
1724 Specify the +:uniq => true+ option to remove duplicates from the collection.
1728 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.
1730 ==== When are Objects Saved?
1732 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.
1734 If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1736 If the parent object (the one declaring the +has_and_belongs_to_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
1738 If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the +_collection_.build+ method.
1740 === Association Callbacks
1742 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.
1744 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:
1751 You define association callbacks by adding options to the association declaration. For example:
1754 -------------------------------------------------------
1755 class Customer < ActiveRecord::Base
1756 has_many :orders, :before_add => :check_credit_limit
1758 def check_credit_limit(order)
1762 -------------------------------------------------------
1764 Rails passes the object being added or removed to the callback.
1766 You can stack callbacks on a single event by passing them as an array:
1769 -------------------------------------------------------
1770 class Customer < ActiveRecord::Base
1771 has_many :orders, :before_add => [:check_credit_limit, :calculate_shipping_charges]
1773 def check_credit_limit(order)
1777 def calculate_shipping_charges(order)
1781 -------------------------------------------------------
1783 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.
1785 === Association Extensions
1787 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:
1790 -------------------------------------------------------
1791 class Customer < ActiveRecord::Base
1793 def find_by_order_prefix(order_number)
1794 find_by_region_id(order_number[0..2])
1798 -------------------------------------------------------
1800 If you have an extension that should be shared by many associations, you can use a named extension module. For example:
1803 -------------------------------------------------------
1804 module FindRecentExtension
1806 find(:all, :conditions => ["created_at > ?", 5.days.ago])
1810 class Customer < ActiveRecord::Base
1811 has_many :orders, :extend => FindRecentExtension
1814 class Supplier < ActiveRecord::Base
1815 has_many :deliveries, :extend => FindRecentExtension
1817 -------------------------------------------------------
1819 To include more than one extension module in a single association, specify an array of names:
1822 -------------------------------------------------------
1823 class Customer < ActiveRecord::Base
1824 has_many :orders, :extend => [FindRecentExtension, FindActiveExtension]
1826 -------------------------------------------------------
1828 Extensions can refer to the internals of the association proxy using these three accessors:
1830 * +proxy_owner+ returns the object that the association is a part of.
1831 * +proxy_reflection+ returns the reflection object that describes the association.
1832 * +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+.
1836 http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11[Lighthouse ticket]
1838 * September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
1839 * September 22, 2008: Added diagrams, misc. cleanup by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
1840 * September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)