association_basics.textile 73.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
h2. A Guide to Active Record Associations

This guide covers the association features of Active Record. By referring to this guide, you will be able to:

* Declare associations between Active Record models
* Understand the various types of Active Record associations
* Use the methods added to your models by creating associations

endprologue.

h3. 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 model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:

<ruby>
class Customer < ActiveRecord::Base
end

class Order < ActiveRecord::Base
end
</ruby>

Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:

<ruby>
@order = Order.create(:order_date => Time.now,
  :customer_id => @customer.id)
</ruby>

Or consider deleting a customer, and ensuring that all of its orders get deleted as well:

<ruby>
33
@orders = Order.where(:customer_id => @customer.id)
34 35 36 37 38 39
@orders.each do |order|
  order.destroy
end
@customer.destroy
</ruby>

40
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:
41 42 43

<ruby>
class Customer < ActiveRecord::Base
44
  has_many :orders, :dependent => :destroy
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
end

class Order < ActiveRecord::Base
  belongs_to :customer
end
</ruby>

With this change, creating a new order for a particular customer is easier:

<ruby>
@order = @customer.orders.create(:order_date => Time.now)
</ruby>

Deleting a customer and all of its orders is _much_ easier:

<ruby>
@customer.destroy
</ruby>

64
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.
65 66 67

h3. The Types of Associations

V
Vijay Dev 已提交
68
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 associations:
69 70 71 72 73 74 75 76 77 78

* +belongs_to+
* +has_one+
* +has_many+
* +has_many :through+
* +has_one :through+
* +has_and_belongs_to_many+

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.

79
h4. The +belongs_to+ Association
80 81 82 83 84 85 86 87 88 89 90

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:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer
end
</ruby>

!images/belongs_to.png(belongs_to Association Diagram)!

91
h4. The +has_one+ Association
92 93 94 95 96 97 98 99 100 101 102

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:

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account
end
</ruby>

!images/has_one.png(has_one Association Diagram)!

103
h4. The +has_many+ Association
104 105 106 107 108 109 110 111 112 113 114 115 116

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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

NOTE: The name of the other model is pluralized when declaring a +has_many+ association.

!images/has_many.png(has_many Association Diagram)!

117
h4. The +has_many :through+ Association
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

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:

<ruby>
class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end
</ruby>

!images/has_many_through.png(has_many :through Association Diagram)!

140 141 142 143 144 145 146 147 148 149
The collection of join models can be managed via the API. For example, if you assign

<ruby>
physician.patients = patients
</ruby>

new join models are created for newly associated objects, and if some are gone their rows are deleted.

WARNING: Automatic deletion of join models is direct, no destroy callbacks are triggered.

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
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:

<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
</ruby>

168 169 170
With +:through => :sections+ specified, Rails will now understand:

<ruby>
171
@document.paragraphs
172 173
</ruby>

174
h4. The +has_one :through+ Association
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

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:

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account
  has_one :account_history, :through => :account
end

class Account < ActiveRecord::Base
  belongs_to :supplier
  has_one :account_history
end

class AccountHistory < ActiveRecord::Base
  belongs_to :account
end
</ruby>

!images/has_one_through.png(has_one :through Association Diagram)!

196
h4. The +has_and_belongs_to_many+ Association
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

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:

<ruby>
class Assembly < ActiveRecord::Base
  has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies
end
</ruby>

!images/habtm.png(has_and_belongs_to_many Association Diagram)!

212
h4. Choosing Between +belongs_to+ and +has_one+
213

214
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?
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

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:

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account
end

class Account < ActiveRecord::Base
  belongs_to :supplier
end
</ruby>

The corresponding migration might look like this:

<ruby>
class CreateSuppliers < ActiveRecord::Migration
232
  def change
233 234 235 236 237 238 239 240 241 242 243 244 245 246
    create_table :suppliers do |t|
      t.string  :name
      t.timestamps
    end

    create_table :accounts do |t|
      t.integer :supplier_id
      t.string  :account_number
      t.timestamps
    end
  end
end
</ruby>

247
NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead.
248

249
h4. Choosing Between +has_many :through+ and +has_and_belongs_to_many+
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

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:

<ruby>
class Assembly < ActiveRecord::Base
  has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies
end
</ruby>

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:

<ruby>
class Assembly < ActiveRecord::Base
  has_many :manifests
  has_many :parts, :through => :manifests
end

class Manifest < ActiveRecord::Base
  belongs_to :assembly
  belongs_to :part
end

class Part < ActiveRecord::Base
  has_many :manifests
  has_many :assemblies, :through => :manifests
end
</ruby>

282
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 in the database).
283 284 285

You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.

286
h4. Polymorphic Associations
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311

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:

<ruby>
class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

class Employee < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end

class Product < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end
</ruby>

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:

<ruby>
class CreatePictures < ActiveRecord::Migration
312
  def change
313 314 315 316 317 318 319 320 321 322 323 324 325 326
    create_table :pictures do |t|
      t.string  :name
      t.integer :imageable_id
      t.string  :imageable_type
      t.timestamps
    end
  end
end
</ruby>

This migration can be simplified by using the +t.references+ form:

<ruby>
class CreatePictures < ActiveRecord::Migration
327
  def change
328
    create_table :pictures do |t|
329
      t.string :name
330 331 332 333 334 335 336 337 338
      t.references :imageable, :polymorphic => true
      t.timestamps
    end
  end
end
</ruby>

!images/polymorphic.png(Polymorphic Association Diagram)!

339
h4. Self Joins
340

341
In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:
342 343 344

<ruby>
class Employee < ActiveRecord::Base
345
  has_many :subordinates, :class_name => "Employee",
346
  belongs_to :manager, :class_name => "Employee"
347
    :foreign_key => "manager_id"
348 349 350 351 352 353 354 355 356 357 358 359 360 361
end
</ruby>

With this setup, you can retrieve +@employee.subordinates+ and +@employee.manager+.

h3. Tips, Tricks, and Warnings

Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:

* Controlling caching
* Avoiding name collisions
* Updating the schema
* Controlling association scope

362
h4. Controlling Caching
363

364
All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

<ruby>
customer.orders                 # retrieves orders from the database
customer.orders.size            # uses the cached copy of orders
customer.orders.empty?          # uses the cached copy of orders
</ruby>

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:

<ruby>
customer.orders                 # retrieves orders from the database
customer.orders.size            # uses the cached copy of orders
customer.orders(true).empty?    # discards the cached copy of orders
                                # and goes back to the database
</ruby>

381
h4. Avoiding Name Collisions
382 383 384

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.

385
h4. Updating the Schema
386 387 388

Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For +belongs_to+ associations you need to create foreign keys, and for +has_and_belongs_to_many+ associations you need to create the appropriate join table.

389
h5. Creating Foreign Keys for +belongs_to+ Associations
390 391 392 393 394 395 396 397 398 399 400 401 402

When you declare a +belongs_to+ association, you need to create foreign keys as appropriate. For example, consider this model:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer
end
</ruby>

This declaration needs to be backed up by the proper foreign key declaration on the orders table:

<ruby>
class CreateOrders < ActiveRecord::Migration
403
  def change
404
    create_table :orders do |t|
405 406 407
      t.datetime :order_date
      t.string   :order_number
      t.integer  :customer_id
408 409 410 411 412 413 414
    end
  end
end
</ruby>

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.

415
h5. Creating Join Tables for +has_and_belongs_to_many+ Associations
416

417
If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
418

419
WARNING: The precedence between model names is calculated using the +&lt;+ 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" (because the underscore '_' is lexicographically _less_ than 's' in common encodings).
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:

<ruby>
class Assembly < ActiveRecord::Base
  has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies
end
</ruby>

These need to be backed up by a migration to create the +assemblies_parts+ table. This table should be created without a primary key:

<ruby>
class CreateAssemblyPartJoinTable < ActiveRecord::Migration
437
  def change
438 439 440 441 442 443 444 445
    create_table :assemblies_parts, :id => false do |t|
      t.integer :assembly_id
      t.integer :part_id
    end
  end
end
</ruby>

446 447
We pass +:id => false+ to +create_table+ because that table does not represent a model. That's required for the association to work properly. If you observe any strange behaviour in a +has_and_belongs_to_many+ association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit.

448
h4. Controlling Association Scope
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

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:

<ruby>
module MyApplication
  module Business
    class Supplier < ActiveRecord::Base
       has_one :account
    end

    class Account < ActiveRecord::Base
       belongs_to :supplier
    end
  end
end
</ruby>

466
This will work fine, because both the +Supplier+ and the +Account+ class are defined within the same scope. But the following will _not_ work, because +Supplier+ and +Account+ are defined in different scopes:
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483

<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
</ruby>

484
To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

<ruby>
module MyApplication
  module Business
    class Supplier < ActiveRecord::Base
       has_one :account,
        :class_name => "MyApplication::Billing::Account"
    end
  end

  module Billing
    class Account < ActiveRecord::Base
       belongs_to :supplier,
        :class_name => "MyApplication::Business::Supplier"
    end
  end
end
</ruby>

h3. Detailed Association Reference

The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.

508
h4. +belongs_to+ Association Reference
509 510 511

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.

512
h5. Methods Added by +belongs_to+
513

514
When you declare a +belongs_to+ association, the declaring class automatically gains four methods related to the association:
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

* <tt><em>association</em>(force_reload = false)</tt>
* <tt><em>association</em>=(associate)</tt>
* <tt>build_<em>association</em>(attributes = {})</tt>
* <tt>create_<em>association</em>(attributes = {})</tt>

In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer
end
</ruby>

Each instance of the order model will have these methods:

<ruby>
customer
customer=
build_customer
create_customer
</ruby>

538
NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix.
539

540
h6(#belongs_to-association). <tt><em>association</em>(force_reload = false)</tt>
541 542 543 544 545 546 547 548 549

The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.

<ruby>
@customer = @order.customer
</ruby>

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.

550
h6(#belongs_to-association_equal). <tt>_association_=(associate)</tt>
551

A
Andreas Scherer 已提交
552
The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
553 554 555 556 557

<ruby>
@order.customer = @customer
</ruby>

558
h6(#belongs_to-build_association). <tt>build_<em>association</em>(attributes = {})</tt>
559 560 561 562

The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.

<ruby>
563 564
@customer = @order.build_customer(:customer_number => 123,
  :customer_name => "John Doe")
565 566
</ruby>

567
h6(#belongs_to-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
568 569 570 571

The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).

<ruby>
572 573
@customer = @order.create_customer(:customer_number => 123,
  :customer_name => "John Doe")
574 575
</ruby>

576 577

h5. Options for +belongs_to+
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599

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:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer, :counter_cache => true,
    :conditions => "active = 1"
end
</ruby>

The +belongs_to+ association supports these options:

* +:autosave+
* +:class_name+
* +:conditions+
* +:counter_cache+
* +:dependent+
* +:foreign_key+
* +:include+
* +:polymorphic+
* +:readonly+
* +:select+
600
* +:touch+
601 602
* +:validate+

603
h6(#belongs_to-autosave). +:autosave+
604 605 606

If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.

607
h6(#belongs_to-class_name). +:class_name+
608 609 610 611 612 613 614 615 616

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:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer, :class_name => "Patron"
end
</ruby>

617
h6(#belongs_to-conditions). +:conditions+
618

619
The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
620 621 622 623 624 625 626

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer, :conditions => "active = 1"
end
</ruby>

627
h6(#belongs_to-counter_cache). +:counter_cache+
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650

The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer
end
class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

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:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer, :counter_cache => true
end
class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

651
With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +size+ method.
652 653 654 655 656 657 658 659 660 661 662 663 664 665

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:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer, :counter_cache => :count_of_orders
end
class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.

666
h6(#belongs_to-dependent). +:dependent+
667

668
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.
669 670 671

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.

672
h6(#belongs_to-foreign_key). +:foreign_key+
673 674 675 676 677 678 679 680 681 682 683 684

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:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer, :class_name => "Patron",
    :foreign_key => "patron_id"
end
</ruby>

TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.

685
h6(#belongs_to-includes). +:include+
686

687
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:
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

<ruby>
class LineItem < ActiveRecord::Base
  belongs_to :order
end

class Order < ActiveRecord::Base
  belongs_to :customer
  has_many :line_items
end

class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

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:

<ruby>
class LineItem < ActiveRecord::Base
  belongs_to :order, :include => :customer
end

class Order < ActiveRecord::Base
  belongs_to :customer
  has_many :line_items
end

class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

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.

723
h6(#belongs_to-polymorphic). +:polymorphic+
724

725
Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
726

727
h6(#belongs_to-readonly). +:readonly+
728 729 730

If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.

731
h6(#belongs_to-select). +:select+
732 733 734 735 736

The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.

TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results.

737
h6(#belongs_to-touch). +:touch+
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758

If you set the +:touch+ option to +:true+, then the +updated_at+ or +updated_on+ timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer, :touch => true
end

class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer, :touch => :orders_updated_at
end
</ruby>

759
h6(#belongs_to-validate). +:validate+
760 761 762

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.

763
h5(#belongs_to-how_to_know_whether_theres_an_associated_object). How To Know Whether There's an Associated Object?
764 765 766 767 768 769 770 771 772

To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>:

<ruby>
if @order.customer.nil?
  @msg = "No customer found for this order"
end
</ruby>

773
h5(#belongs_to-when_are_objects_saved). When are Objects Saved?
774 775 776

Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.

777
h4. +has_one+ Association Reference
778 779 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.

781
h5. Methods Added by +has_one+
782

783
When you declare a +has_one+ association, the declaring class automatically gains four methods related to the association:
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806

* <tt><em>association</em>(force_reload = false)</tt>
* <tt><em>association</em>=(associate)</tt>
* <tt>build_<em>association</em>(attributes = {})</tt>
* <tt>create_<em>association</em>(attributes = {})</tt>

In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration:

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account
end
</ruby>

Each instance of the +Supplier+ model will have these methods:

<ruby>
account
account=
build_account
create_account
</ruby>

807
NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix.
808

809
h6(#has_one-association). <tt><em>association</em>(force_reload = false)</tt>
810 811 812 813 814 815 816 817 818

The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.

<ruby>
@account = @supplier.account
</ruby>

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.

819
h6(#has_one-association_equal). <tt><em>association</em>=(associate)</tt>
820 821 822 823 824 825 826

The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.

<ruby>
@supplier.account = @account
</ruby>

827
h6(#has_one-build_association). <tt>build_<em>association</em>(attributes = {})</tt>
828 829 830 831

The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.

<ruby>
832
@account = @supplier.build_account(:terms => "Net 30")
833 834
</ruby>

835
h6(#has_one-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
836 837 838 839

The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).

<ruby>
840
@account = @supplier.create_account(:terms => "Net 30")
841 842
</ruby>

843
h5. Options for +has_one+
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870

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:

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account, :class_name => "Billing", :dependent => :nullify
end
</ruby>

The +has_one+ association supports these options:

* +:as+
* +:autosave+
* +:class_name+
* +:conditions+
* +:dependent+
* +:foreign_key+
* +:include+
* +:order+
* +:primary_key+
* +:readonly+
* +:select+
* +:source+
* +:source_type+
* +:through+
* +:validate+

871
h6(#has_one-as). +:as+
872

873
Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
874

875
h6(#has_one-autosave). +:autosave+
876 877 878

If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.

879
h6(#has_one-class_name). +:class_name+
880

881
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:
882 883 884 885 886 887 888

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account, :class_name => "Billing"
end
</ruby>

889
h6(#has_one-conditions). +:conditions+
890

891
The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
892 893 894 895 896 897 898

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account, :conditions => "confirmed = 1"
end
</ruby>

899
h6(#has_one-dependent). +:dependent+
900

901
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+.
902

903
h6(#has_one-foreign_key). +:foreign_key+
904 905 906 907 908 909 910 911 912 913 914

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:

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account, :foreign_key => "supp_id"
end
</ruby>

TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.

915
h6(#has_one-include). +:include+
916

917
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:
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account
end

class Account < ActiveRecord::Base
  belongs_to :supplier
  belongs_to :representative
end

class Representative < ActiveRecord::Base
  has_many :accounts
end
</ruby>

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:

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account, :include => :representative
end

class Account < ActiveRecord::Base
  belongs_to :supplier
  belongs_to :representative
end

class Representative < ActiveRecord::Base
  has_many :accounts
end
</ruby>

951
h6(#has_one-order). +:order+
952

953
The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
954

955
h6(#has_one-primary_key). +:primary_key+
956 957 958

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.

959
h6(#has_one-readonly). +:readonly+
960 961 962

If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.

963
h6(#has_one-select). +:select+
964 965 966

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.

967
h6(#has_one-source). +:source+
968 969 970

The +:source+ option specifies the source association name for a +has_one :through+ association.

971
h6(#has_one-source_type). +:source_type+
972 973 974

The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.

975
h6(#has_one-through). +:through+
976

977
The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has_one-through-association">earlier in this guide</a>.
978

979
h6(#has_one-validate). +:validate+
980 981 982

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.

983
h5(#has_one-how_to_know_whether_theres_an_associated_object). How To Know Whether There's an Associated Object?
984 985 986 987 988 989 990 991 992

To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>:

<ruby>
if @supplier.account.nil?
  @msg = "No account found for this supplier"
end
</ruby>

993
h5(#has_one-when_are_objects_saved). When are Objects Saved?
994 995 996 997 998

When you assign an object to a +has_one+ association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.

If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.

999
If the parent object (the one declaring the +has_one+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved. They will automatically when the parent object is saved.
1000 1001 1002

If you want to assign an object to a +has_one+ association without saving the object, use the <tt><em>association</em>.build</tt> method.

1003
h4. +has_many+ Association Reference
1004 1005 1006

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.

1007
h5. Methods Added by +has_many+
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:

* <tt><em>collection</em>(force_reload = false)</tt>
* <tt><em>collection</em><<(object, ...)</tt>
* <tt><em>collection</em>.delete(object, ...)</tt>
* <tt><em>collection</em>=objects</tt>
* <tt><em>collection_singular</em>_ids</tt>
* <tt><em>collection_singular</em>_ids=ids</tt>
* <tt><em>collection</em>.clear</tt>
* <tt><em>collection</em>.empty?</tt>
* <tt><em>collection</em>.size</tt>
* <tt><em>collection</em>.find(...)</tt>
1021
* <tt><em>collection</em>.where(...)</tt>
1022
* <tt><em>collection</em>.exists?(...)</tt>
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
* <tt><em>collection</em>.build(attributes = {}, ...)</tt>
* <tt><em>collection</em>.create(attributes = {})</tt>

In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

Each instance of the customer model will have these methods:

<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(...)
1047
orders.where(...)
1048
orders.exists?(...)
1049 1050 1051 1052
orders.build(attributes = {}, ...)
orders.create(attributes = {})
</ruby>

1053
h6(#has_many-collection). <tt><em>collection</em>(force_reload = false)</tt>
1054 1055 1056 1057 1058 1059 1060

The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.

<ruby>
@orders = @customer.orders
</ruby>

1061
h6(#has_many-collection-lt_lt). <tt><em>collection</em><<(object, ...)</tt>
1062 1063 1064 1065 1066 1067 1068

The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.

<ruby>
@customer.orders << @order1
</ruby>

1069
h6(#has_many-collection-delete). <tt><em>collection</em>.delete(object, ...)</tt>
1070 1071 1072 1073 1074 1075 1076

The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to +NULL+.

<ruby>
@customer.orders.delete(@order1)
</ruby>

1077
WARNING: Additionally, objects will be destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
1078 1079


1080
h6(#has_many-collection-equal). <tt><em>collection</em>=objects</tt>
1081

1082
The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1083

1084
h6(#has_many-collection_singular). <tt><em>collection_singular</em>_ids</tt>
1085 1086 1087 1088 1089 1090 1091

The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.

<ruby>
@order_ids = @customer.order_ids
</ruby>

1092
h6(#has_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt>
1093 1094 1095

The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.

1096
h6(#has_many-collection-clear). <tt><em>collection</em>.clear</tt>
1097 1098 1099

The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+.

1100
h6(#has_many-collection-empty). <tt><em>collection</em>.empty?</tt>
1101 1102 1103 1104 1105 1106 1107 1108 1109

The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.

<ruby>
<% if @customer.orders.empty? %>
  No Orders Found
<% end %>
</ruby>

1110
h6(#has_many-collection-size). <tt><em>collection</em>.size</tt>
1111 1112 1113 1114 1115 1116 1117

The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.

<ruby>
@order_count = @customer.orders.size
</ruby>

1118
h6(#has_many-collection-find). <tt><em>collection</em>.find(...)</tt>
1119 1120 1121 1122

The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.

<ruby>
1123
@open_orders = @customer.orders.all(:conditions => "open = 1")
1124 1125
</ruby>

1126
NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
1127

1128
h6(#has_many-collection-where). <tt><em>collection</em>.where(...)</tt>
1129 1130 1131 1132

The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.

<ruby>
1133 1134
@open_orders = @customer.orders.where(:open => true) # No query yet
@open_order = @open_orders.first # Now the database will be queried
1135 1136 1137
</ruby>

h6(#has_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt>
1138

1139
The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
1140

1141
h6(#has_many-collection-build). <tt><em>collection</em>.build(attributes = {}, ...)</tt>
1142 1143 1144 1145

The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.

<ruby>
1146 1147
@order = @customer.orders.build(:order_date => Time.now,
  :order_number => "A12345")
1148 1149
</ruby>

1150
h6(#has_many-collection-create). <tt><em>collection</em>.create(attributes = {})</tt>
1151 1152 1153 1154

The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations).

<ruby>
1155 1156
@order = @customer.orders.create(:order_date => Time.now,
  :order_number => "A12345")
1157 1158
</ruby>

1159
h5. Options for +has_many+
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193

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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders, :dependent => :delete_all, :validate => :false
end
</ruby>

The +has_many+ association supports these options:

* +:as+
* +:autosave+
* +: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+

1194
h6(#has_many-as). +:as+
1195

1196
Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.
1197

1198
h6(#has_many-autosave). +:autosave+
1199 1200 1201

If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.

1202
h6(#has_many-class_name). +:class_name+
1203 1204 1205 1206 1207 1208 1209 1210 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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders, :class_name => "Transaction"
end
</ruby>

1212
h6(#has_many-conditions). +:conditions+
1213

1214
The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233

<ruby>
class Customer < ActiveRecord::Base
  has_many :confirmed_orders, :class_name => "Order",
    :conditions => "confirmed = 1"
end
</ruby>

You can also set conditions via a hash:

<ruby>
class Customer < ActiveRecord::Base
  has_many :confirmed_orders, :class_name => "Order",
    :conditions => { :confirmed => true }
end
</ruby>

If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.

P
Pratik Naik 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
If you need to evaluate conditions dynamically at runtime, you could use string interpolation in single quotes:

<ruby>
class Customer < ActiveRecord::Base
  has_many :latest_orders, :class_name => "Order",
    :conditions => 'orders.created_at > #{10.hours.ago.to_s(:db).inspect}'
end
</ruby>

Be sure to use single quotes.

1245
h6(#has_many-counter_sql). +:counter_sql+
1246 1247 1248 1249 1250

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.

1251
h6(#has_many-dependent). +:dependent+
1252

1253
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+.
1254 1255 1256

NOTE: This option is ignored when you use the +:through+ option on the association.

1257
h6(#has_many-extend). +:extend+
1258

1259
The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
1260

1261
h6(#has_many-finder_sql). +:finder_sql+
1262 1263 1264

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.

1265
h6(#has_many-foreign_key). +:foreign_key+
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276

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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders, :foreign_key => "cust_id"
end
</ruby>

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
h6(#has_many-group). +:group+
1278 1279 1280 1281 1282 1283 1284 1285 1286

The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.

<ruby>
class Customer < ActiveRecord::Base
  has_many :line_items, :through => :orders, :group => "orders.id"
end
</ruby>

1287
h6(#has_many-include). +:include+
1288

1289
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:
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :customer
  has_many :line_items
end

class LineItem < ActiveRecord::Base
  belongs_to :order
end
</ruby>

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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders, :include => :line_items
end

class Order < ActiveRecord::Base
  belongs_to :customer
  has_many :line_items
end

class LineItem < ActiveRecord::Base
  belongs_to :order
end
</ruby>

1323
h6(#has_many-limit). +:limit+
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333

The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.

<ruby>
class Customer < ActiveRecord::Base
  has_many :recent_orders, :class_name => "Order",
    :order => "order_date DESC", :limit => 100
end
</ruby>

1334
h6(#has_many-offset). +:offset+
1335 1336 1337

The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.

1338
h6(#has_many-order). +:order+
1339

1340
The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
1341 1342 1343 1344 1345 1346 1347

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders, :order => "date_confirmed DESC"
end
</ruby>

1348
h6(#has_many-primary_key). +:primary_key+
1349

1350
By convention, Rails guesses that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
1351

1352
h6(#has_many-readonly). +:readonly+
1353 1354 1355

If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.

1356
h6(#has_many-select). +:select+
1357 1358 1359 1360 1361

The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.

WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.

1362
h6(#has_many-source). +:source+
1363 1364 1365

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.

1366
h6(#has_many-source_type). +:source_type+
1367 1368 1369

The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.

1370
h6(#has_many-through). +:through+
1371

1372
The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has_many-through-association">earlier in this guide</a>.
1373

1374
h6(#has_many-uniq). +:uniq+
1375

1376
Set the +:uniq+ option to true to keep the collection free of duplicates. This is mostly useful together with the +:through+ option.
1377 1378 1379

<ruby>
class Person < ActiveRecord::Base
1380 1381
  has_many :readings
  has_many :posts, :through => :readings
1382
end
1383 1384 1385 1386 1387 1388 1389

person = Person.create(:name => 'john')
post   = Post.create(:name => 'a1')
person.posts << post
person.posts << post
person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5, name: "a1">]
Reading.all.inspect  # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Reading id: 13, person_id: 5, post_id: 5>]
1390 1391
</ruby>

1392
In the above case there are two readings and +person.posts+ brings out both of them even though these records are pointing to the same post.
1393

1394
Now let's set +:uniq+ to true:
1395 1396 1397

<ruby>
class Person
1398 1399
  has_many :readings
  has_many :posts, :through => :readings, :uniq => true
1400
end
1401 1402 1403 1404 1405

person = Person.create(:name => 'honda')
post   = Post.create(:name => 'a1')
person.posts << post
person.posts << post
1406 1407
person.posts.inspect # => [#<Post id: 7, name: "a1">]
Reading.all.inspect  # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>]
1408 1409
</ruby>

1410
In the above case there are still two readings. However +person.posts+ shows only one post because the collection loads only unique records.
1411

1412
h6(#has_many-validate). +:validate+
1413 1414 1415

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.

1416
h5(#has_many-when_are_objects_saved). When are Objects Saved?
1417 1418 1419 1420 1421 1422 1423 1424 1425

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.

If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.

If the parent object (the one declaring the +has_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.

If you want to assign an object to a +has_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method.

1426
h4. +has_and_belongs_to_many+ Association Reference
1427 1428 1429

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.

1430
h5. Methods Added by +has_and_belongs_to_many+
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443

When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:

* <tt><em>collection</em>(force_reload = false)</tt>
* <tt><em>collection</em><<(object, ...)</tt>
* <tt><em>collection</em>.delete(object, ...)</tt>
* <tt><em>collection</em>=objects</tt>
* <tt><em>collection_singular</em>_ids</tt>
* <tt><em>collection_singular</em>_ids=ids</tt>
* <tt><em>collection</em>.clear</tt>
* <tt><em>collection</em>.empty?</tt>
* <tt><em>collection</em>.size</tt>
* <tt><em>collection</em>.find(...)</tt>
1444
* <tt><em>collection</em>.where(...)</tt>
1445
* <tt><em>collection</em>.exists?(...)</tt>
1446 1447 1448
* <tt><em>collection</em>.build(attributes = {})</tt>
* <tt><em>collection</em>.create(attributes = {})</tt>

1449
In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol. For example, given the declaration:
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

<ruby>
class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies
end
</ruby>

Each instance of the part model will have these methods:

<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(...)
1470
assemblies.where(...)
1471
assemblies.exists?(...)
1472 1473 1474 1475
assemblies.build(attributes = {}, ...)
assemblies.create(attributes = {})
</ruby>

1476
h6. Additional Column Methods
1477 1478 1479 1480 1481 1482

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+.


1483
h6(#has_and_belongs_to_many-collection). <tt><em>collection</em>(force_reload = false)</tt>
1484 1485 1486 1487 1488 1489 1490

The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.

<ruby>
@assemblies = @part.assemblies
</ruby>

1491
h6(#has_and_belongs_to_many-collection-lt_lt). <tt><em>collection</em><<(object, ...)</tt>
1492 1493 1494 1495 1496 1497 1498 1499 1500

The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table.

<ruby>
@part.assemblies << @assembly1
</ruby>

NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.

1501
h6(#has_and_belongs_to_many-collection-delete). <tt><em>collection</em>.delete(object, ...)</tt>
1502 1503 1504 1505 1506 1507 1508

The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.

<ruby>
@part.assemblies.delete(@assembly1)
</ruby>

1509
h6(#has_and_belongs_to_many-collection-equal). <tt><em>collection</em>=objects</tt>
1510 1511 1512

The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.

1513
h6(#has_and_belongs_to_many-collection_singular). <tt><em>collection_singular</em>_ids</tt>
1514 1515 1516 1517 1518 1519 1520

The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.

<ruby>
@assembly_ids = @part.assembly_ids
</ruby>

1521
h6(#has_and_belongs_to_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt>
1522 1523 1524

The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.

1525
h6(#has_and_belongs_to_many-collection-clear). <tt><em>collection</em>.clear</tt>
1526

1527
The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
1528

1529
h6(#has_and_belongs_to_many-collection-empty). <tt><em>collection</em>.empty?</tt>
1530 1531 1532 1533 1534 1535 1536 1537 1538

The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.

<ruby>
<% if @part.assemblies.empty? %>
  This part is not used in any assemblies
<% end %>
</ruby>

1539
h6(#has_and_belongs_to_many-collection-size). <tt><em>collection</em>.size</tt>
1540 1541 1542 1543 1544 1545 1546

The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.

<ruby>
@assembly_count = @part.assemblies.size
</ruby>

1547
h6(#has_and_belongs_to_many-collection-find). <tt><em>collection</em>.find(...)</tt>
1548 1549 1550 1551

The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.

<ruby>
1552
@new_assemblies = @part.assemblies.all(
1553 1554 1555
  :conditions => ["created_at > ?", 2.days.ago])
</ruby>

1556
NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
1557

1558
h6(#has_and_belongs_to_many-collection-where). <tt><em>collection</em>.where(...)</tt>
1559 1560 1561 1562 1563 1564 1565

The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.

<ruby>
@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
</ruby>

1566
h6(#has_and_belongs_to_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt>
1567

1568
The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
1569

1570
h6(#has_and_belongs_to_many-collection-build). <tt><em>collection</em>.build(attributes = {})</tt>
1571 1572 1573 1574 1575 1576 1577 1578

The <tt><em>collection</em>.build</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.

<ruby>
@assembly = @part.assemblies.build(
  {:assembly_name => "Transmission housing"})
</ruby>

1579
h6(#has_and_belongs_to_many-create-attributes). <tt><em>collection</em>.create(attributes = {})</tt>
1580

1581
The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and the associated object _will_ be saved (assuming that it passes any validations).
1582 1583 1584 1585 1586 1587

<ruby>
@assembly = @part.assemblies.create(
  {:assembly_name => "Transmission housing"})
</ruby>

1588
h5. Options for +has_and_belongs_to_many+
1589

1590
In many situations, you can use the default behavior for +has_and_belongs_to_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_and_belongs_to_many+ association. For example, an association with several options might look like this:
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621

<ruby>
class Parts < ActiveRecord::Base
  has_and_belongs_to_many :assemblies, :uniq => true,
    :read_only => true
end
</ruby>

The +has_and_belongs_to_many+ association supports these options:

* +:association_foreign_key+
* +:autosave+
* +: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+

1622
h6(#has_and_belongs_to_many-association_foreign_key). +:association_foreign_key+
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

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:

TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:

<ruby>
class User < ActiveRecord::Base
  has_and_belongs_to_many :friends, :class_name => "User",
    :foreign_key => "this_user_id",
    :association_foreign_key => "other_user_id"
end
</ruby>

1636
h6(#has_and_belongs_to_many-autosave). +:autosave+
1637 1638 1639

If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.

1640
h6(#has_and_belongs_to_many-class_name). +:class_name+
1641 1642 1643 1644 1645 1646 1647 1648 1649

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:

<ruby>
class Parts < ActiveRecord::Base
  has_and_belongs_to_many :assemblies, :class_name => "Gadget"
end
</ruby>

1650
h6(#has_and_belongs_to_many-conditions). +:conditions+
1651

1652
The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669

<ruby>
class Parts < ActiveRecord::Base
  has_and_belongs_to_many :assemblies,
    :conditions => "factory = 'Seattle'"
end
</ruby>

You can also set conditions via a hash:

<ruby>
class Parts < ActiveRecord::Base
  has_and_belongs_to_many :assemblies,
    :conditions => { :factory => 'Seattle' }
end
</ruby>

1670
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".
1671

1672
h6(#has_and_belongs_to_many-counter_sql). +:counter_sql+
1673 1674 1675 1676 1677

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.

1678
h6(#has_and_belongs_to_many-delete_sql). +:delete_sql+
1679 1680 1681

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.

1682
h6(#has_and_belongs_to_many-extend). +:extend+
1683

1684
The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
1685

1686
h6(#has_and_belongs_to_many-finder_sql). +:finder_sql+
1687 1688 1689

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.

1690
h6(#has_and_belongs_to_many-foreign_key). +:foreign_key+
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

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:

<ruby>
class User < ActiveRecord::Base
  has_and_belongs_to_many :friends, :class_name => "User",
    :foreign_key => "this_user_id",
    :association_foreign_key => "other_user_id"
end
</ruby>

1702
h6(#has_and_belongs_to_many-group). +:group+
1703 1704 1705 1706 1707 1708 1709 1710 1711

The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.

<ruby>
class Parts < ActiveRecord::Base
  has_and_belongs_to_many :assemblies, :group => "factory"
end
</ruby>

1712
h6(#has_and_belongs_to_many-include). +:include+
1713

1714
You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used.
1715

1716
h6(#has_and_belongs_to_many-insert_sql). +:insert_sql+
1717 1718 1719

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.

1720
h6(#has_and_belongs_to_many-join_table). +:join_table+
1721 1722 1723

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.

1724
h6(#has_and_belongs_to_many-limit). +:limit+
1725 1726 1727 1728 1729 1730

The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.

<ruby>
class Parts < ActiveRecord::Base
  has_and_belongs_to_many :assemblies, :order => "created_at DESC",
1731
    :limit => 50
1732 1733 1734
end
</ruby>

1735
h6(#has_and_belongs_to_many-offset). +:offset+
1736 1737 1738

The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.

1739
h6(#has_and_belongs_to_many-order). +:order+
1740

1741
The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
1742 1743 1744 1745 1746 1747 1748

<ruby>
class Parts < ActiveRecord::Base
  has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
end
</ruby>

1749
h6(#has_and_belongs_to_many-readonly). +:readonly+
1750 1751 1752

If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.

1753
h6(#has_and_belongs_to_many-select). +:select+
1754 1755 1756

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.

1757
h6(#has_and_belongs_to_many-uniq). +:uniq+
1758 1759 1760

Specify the +:uniq => true+ option to remove duplicates from the collection.

1761
h6(#has_and_belongs_to_many-validate). +:validate+
1762 1763 1764

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.

1765
h5(#has_and_belongs_to_many-when_are_objects_saved). When are Objects Saved?
1766 1767 1768 1769 1770 1771 1772 1773 1774

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.

If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.

If the parent object (the one declaring the +has_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.

If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method.

1775
h4. Association Callbacks
1776

1777
Normal callbacks hook into the life cycle 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.
1778

1779
Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks:
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818

* +before_add+
* +after_add+
* +before_remove+
* +after_remove+

You define association callbacks by adding options to the association declaration. For example:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders, :before_add => :check_credit_limit

  def check_credit_limit(order)
    ...
  end
end
</ruby>

Rails passes the object being added or removed to the callback.

You can stack callbacks on a single event by passing them as an array:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders,
    :before_add => [:check_credit_limit, :calculate_shipping_charges]

  def check_credit_limit(order)
    ...
  end

  def calculate_shipping_charges(order)
    ...
  end
end
</ruby>

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.

1819
h4. Association Extensions
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837

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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders do
    def find_by_order_prefix(order_number)
      find_by_region_id(order_number[0..2])
    end
  end
end
</ruby>

If you have an extension that should be shared by many associations, you can use a named extension module. For example:

<ruby>
module FindRecentExtension
  def find_recent
1838
    where("created_at > ?", 5.days.ago)
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
  end
end

class Customer < ActiveRecord::Base
  has_many :orders, :extend => FindRecentExtension
end

class Supplier < ActiveRecord::Base
  has_many :deliveries, :extend => FindRecentExtension
end
</ruby>

1851
To include more than one extension module in a single association, specify an array of modules:
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders,
    :extend => [FindRecentExtension, FindActiveExtension]
end
</ruby>

Extensions can refer to the internals of the association proxy using these three accessors:

* +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+.

h3. Changelog

1868
* April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
1869
* April 19, 2009: Added +:touch+ option to +belongs_to+ associations by "Mike Gunderloy":credits.html#mgunderloy
1870 1871 1872 1873
* February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy
* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by "Mike Gunderloy":credits.html#mgunderloy . First release version.
* September 22, 2008: Added diagrams, misc. cleanup by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
* September 14, 2008: initial version by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)