association_basics.md 83.4 KB
Newer Older
1
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
X
Xavier Noria 已提交
2

S
Steve Klabnik 已提交
3 4
Active Record Associations
==========================
5

6 7 8
This guide covers the association features of Active Record.

After reading this guide, you will know:
9

10 11 12
* How to declare associations between Active Record models.
* How to understand the various types of Active Record associations.
* How to use the methods added to your models by creating associations.
13 14 15 16 17 18

--------------------------------------------------------------------------------

Why Associations?
-----------------

19
In Rails, an _association_ is a connection between two Active Record models. 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 authors and a model for books. Each author can have many books. Without associations, the model declarations would look like this:
20 21

```ruby
22
class Author < ApplicationRecord
23 24
end

25
class Book < ApplicationRecord
26 27 28
end
```

29
Now, suppose we wanted to add a new book for an existing author. We'd need to do something like this:
30 31

```ruby
32
@book = Book.create(published_at: Time.now, author_id: @author.id)
33 34
```

35
Or consider deleting an author, and ensuring that all of its books get deleted as well:
36 37

```ruby
38 39 40
@books = Book.where(author_id: @author.id)
@books.each do |book|
  book.destroy
41
end
42
@author.destroy
43 44
```

45
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 authors and books:
46 47

```ruby
48 49
class Author < ApplicationRecord
  has_many :books, dependent: :destroy
50 51
end

52 53
class Book < ApplicationRecord
  belongs_to :author
54 55 56
end
```

57
With this change, creating a new book for a particular author is easier:
58 59

```ruby
60
@book = @author.books.create(published_at: Time.now)
61 62
```

63
Deleting an author and all of its books is *much* easier:
64 65

```ruby
66
@author.destroy
67 68 69 70 71 72 73
```

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.

The Types of Associations
-------------------------

R
raq929 已提交
74
Rails supports six types of associations:
75 76 77 78 79 80 81 82

* `belongs_to`
* `has_one`
* `has_many`
* `has_many :through`
* `has_one :through`
* `has_and_belongs_to_many`

R
raq929 已提交
83 84
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](https://en.wikipedia.org/wiki/Unique_key)-[Foreign Key](https://en.wikipedia.org/wiki/Foreign_key) information between instances of the two models, and you also get a number of utility methods added to your model.

85 86 87 88
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.

### The `belongs_to` Association

89
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 authors and books, and each book can be assigned to exactly one author, you'd declare the book model this way:
90 91

```ruby
92 93
class Book < ApplicationRecord
  belongs_to :author
94 95 96
end
```

97
![belongs_to Association Diagram](images/association_basics/belongs_to.png)
98

99
NOTE: `belongs_to` associations _must_ use the singular term. If you used the pluralized form in the above example for the `author` association in the `Book` model, you would be told that there was an "uninitialized constant Book::Authors". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.
100

101 102 103
The corresponding migration might look like this:

```ruby
104
class CreateBooks < ActiveRecord::Migration[5.0]
105
  def change
106
    create_table :authors do |t|
107
      t.string :name
108
      t.timestamps
109 110
    end

111 112 113
    create_table :books do |t|
      t.belongs_to :author, index: true
      t.datetime :published_at
114
      t.timestamps
115 116 117 118 119
    end
  end
end
```

120 121 122 123 124
### The `has_one` Association

A `has_one` association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:

```ruby
125
class Supplier < ApplicationRecord
126 127 128 129
  has_one :account
end
```

130
![has_one Association Diagram](images/association_basics/has_one.png)
131

132 133 134
The corresponding migration might look like this:

```ruby
135
class CreateSuppliers < ActiveRecord::Migration[5.0]
136 137 138
  def change
    create_table :suppliers do |t|
      t.string :name
139
      t.timestamps
140 141 142
    end

    create_table :accounts do |t|
143
      t.belongs_to :supplier, index: true
144
      t.string :account_number
145
      t.timestamps
146 147 148 149 150
    end
  end
end
```

151 152 153
Depending on the use case, you might also need to create a unique index and/or
a foreign key constraint on the supplier column for the accounts table. In this
case, the column definition might look like this:
154 155

```ruby
156
create_table :accounts do |t|
157
  t.belongs_to :supplier, index: { unique: true }, foreign_key: true
158 159
  # ...
end
160 161
```

162 163
### The `has_many` Association

164
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 authors and books, the author model could be declared like this:
165 166

```ruby
167 168
class Author < ApplicationRecord
  has_many :books
169 170 171 172 173
end
```

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

174
![has_many Association Diagram](images/association_basics/has_many.png)
175

176 177 178
The corresponding migration might look like this:

```ruby
179
class CreateAuthors < ActiveRecord::Migration[5.0]
180
  def change
181
    create_table :authors do |t|
182
      t.string :name
183
      t.timestamps
184 185
    end

186 187 188
    create_table :books do |t|
      t.belongs_to :author, index: true
      t.datetime :published_at
189
      t.timestamps
190 191 192 193 194
    end
  end
end
```

195 196 197 198 199
### The `has_many :through` Association

A `has_many :through` association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:

```ruby
200
class Physician < ApplicationRecord
201
  has_many :appointments
202
  has_many :patients, through: :appointments
203 204
end

205
class Appointment < ApplicationRecord
206 207 208 209
  belongs_to :physician
  belongs_to :patient
end

210
class Patient < ApplicationRecord
211
  has_many :appointments
V
Vijay Dev 已提交
212
  has_many :physicians, through: :appointments
213 214 215
end
```

216
![has_many :through Association Diagram](images/association_basics/has_many_through.png)
217

218 219 220
The corresponding migration might look like this:

```ruby
221
class CreateAppointments < ActiveRecord::Migration[5.0]
222 223 224
  def change
    create_table :physicians do |t|
      t.string :name
225
      t.timestamps
226 227 228 229
    end

    create_table :patients do |t|
      t.string :name
230
      t.timestamps
231 232 233
    end

    create_table :appointments do |t|
234 235
      t.belongs_to :physician, index: true
      t.belongs_to :patient, index: true
236
      t.datetime :appointment_date
237
      t.timestamps
238 239 240 241 242
    end
  end
end
```

243 244
The collection of join models can be managed via the [`has_many` association methods](#has-many-association-reference).
For example, if you assign:
245 246 247 248 249

```ruby
physician.patients = patients
```

250 251
Then new join models are automatically created for the newly associated objects.
If some that existed previously are now missing, then their join rows are automatically deleted.
252 253 254 255 256 257

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

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
258
class Document < ApplicationRecord
259
  has_many :sections
260
  has_many :paragraphs, through: :sections
261 262
end

263
class Section < ApplicationRecord
264 265 266 267
  belongs_to :document
  has_many :paragraphs
end

268
class Paragraph < ApplicationRecord
269 270 271 272
  belongs_to :section
end
```

273
With `through: :sections` specified, Rails will now understand:
274 275 276 277 278 279 280

```ruby
@document.paragraphs
```

### The `has_one :through` Association

281 282 283 284
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
supplier model could look like this:
285 286

```ruby
287
class Supplier < ApplicationRecord
288
  has_one :account
289
  has_one :account_history, through: :account
290 291
end

292
class Account < ApplicationRecord
293 294 295 296
  belongs_to :supplier
  has_one :account_history
end

297
class AccountHistory < ApplicationRecord
298 299 300 301
  belongs_to :account
end
```

302
![has_one :through Association Diagram](images/association_basics/has_one_through.png)
303

304 305 306
The corresponding migration might look like this:

```ruby
307
class CreateAccountHistories < ActiveRecord::Migration[5.0]
308 309 310
  def change
    create_table :suppliers do |t|
      t.string :name
311
      t.timestamps
312 313 314
    end

    create_table :accounts do |t|
315
      t.belongs_to :supplier, index: true
316
      t.string :account_number
317
      t.timestamps
318 319 320
    end

    create_table :account_histories do |t|
321
      t.belongs_to :account, index: true
322
      t.integer :credit_rating
323
      t.timestamps
324 325 326 327 328
    end
  end
end
```

329 330 331 332 333
### The `has_and_belongs_to_many` Association

A `has_and_belongs_to_many` association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:

```ruby
334
class Assembly < ApplicationRecord
335 336 337
  has_and_belongs_to_many :parts
end

338
class Part < ApplicationRecord
339 340 341 342
  has_and_belongs_to_many :assemblies
end
```

343
![has_and_belongs_to_many Association Diagram](images/association_basics/habtm.png)
344

345 346 347
The corresponding migration might look like this:

```ruby
348
class CreateAssembliesAndParts < ActiveRecord::Migration[5.0]
349 350 351
  def change
    create_table :assemblies do |t|
      t.string :name
352
      t.timestamps
353 354 355 356
    end

    create_table :parts do |t|
      t.string :part_number
357
      t.timestamps
358 359
    end

360
    create_table :assemblies_parts, id: false do |t|
361 362
      t.belongs_to :assembly, index: true
      t.belongs_to :part, index: true
363 364 365 366 367
    end
  end
end
```

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
As you can see we don't create the relevant model for `assemblies_parts` table, So We can't create the many-to-many record like this

``` ruby
AssemblyPart.create(assembly: @assembly, part: @part) # => NameError: uninitialized constant AssemblyPart
```

If you want to create the relevant many-to-many record, you can use the below code

``` ruby
@assembly.parts << @part
# Or
@part.assemblies << @assembly
```

They are equivalent.

384 385 386 387 388 389 390
### Choosing Between `belongs_to` and `has_one`

If you want to set up a one-to-one 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?

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
391
class Supplier < ApplicationRecord
392 393 394
  has_one :account
end

395
class Account < ApplicationRecord
396 397 398 399 400 401 402
  belongs_to :supplier
end
```

The corresponding migration might look like this:

```ruby
403
class CreateSuppliers < ActiveRecord::Migration[5.0]
404 405
  def change
    create_table :suppliers do |t|
N
Neodelf 已提交
406
      t.string :name
407
      t.timestamps
408 409 410 411 412
    end

    create_table :accounts do |t|
      t.integer :supplier_id
      t.string  :account_number
413
      t.timestamps
414
    end
415 416

    add_index :accounts, :supplier_id
417 418 419 420 421 422 423 424 425 426 427
  end
end
```

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

### Choosing Between `has_many :through` and `has_and_belongs_to_many`

Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use `has_and_belongs_to_many`, which allows you to make the association directly:

```ruby
428
class Assembly < ApplicationRecord
429 430 431
  has_and_belongs_to_many :parts
end

432
class Part < ApplicationRecord
433 434 435 436 437 438 439
  has_and_belongs_to_many :assemblies
end
```

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
440
class Assembly < ApplicationRecord
441
  has_many :manifests
442
  has_many :parts, through: :manifests
443 444
end

445
class Manifest < ApplicationRecord
446 447 448 449
  belongs_to :assembly
  belongs_to :part
end

450
class Part < ApplicationRecord
451
  has_many :manifests
452
  has_many :assemblies, through: :manifests
453 454 455 456 457
end
```

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

A
Anthony Crumley 已提交
458
You should use `has_many :through` if you need validations, callbacks, or extra attributes on the join model.
459 460 461 462 463 464

### Polymorphic Associations

A slightly more advanced twist on associations is the _polymorphic association_. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:

```ruby
465
class Picture < ApplicationRecord
466
  belongs_to :imageable, polymorphic: true
467 468
end

469
class Employee < ApplicationRecord
470
  has_many :pictures, as: :imageable
471 472
end

473
class Product < ApplicationRecord
474
  has_many :pictures, as: :imageable
475 476 477 478 479 480 481 482 483 484
end
```

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
485
class CreatePictures < ActiveRecord::Migration[5.0]
486 487 488 489 490
  def change
    create_table :pictures do |t|
      t.string  :name
      t.integer :imageable_id
      t.string  :imageable_type
491
      t.timestamps
492
    end
493

494
    add_index :pictures, [:imageable_type, :imageable_id]
495 496 497 498 499 500 501
  end
end
```

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

```ruby
502
class CreatePictures < ActiveRecord::Migration[5.0]
503 504 505
  def change
    create_table :pictures do |t|
      t.string :name
506
      t.references :imageable, polymorphic: true, index: true
507
      t.timestamps
508 509 510 511 512
    end
  end
end
```

513
![Polymorphic Association Diagram](images/association_basics/polymorphic.png)
514 515 516 517 518 519

### Self Joins

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

```ruby
520
class Employee < ApplicationRecord
521 522 523
  has_many :subordinates, class_name: "Employee",
                          foreign_key: "manager_id"

524
  belongs_to :manager, class_name: "Employee", optional: true
525 526 527 528 529
end
```

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

530 531 532
In your migrations/schema, you will add a references column to the model itself.

```ruby
533
class CreateEmployees < ActiveRecord::Migration[5.0]
534 535
  def change
    create_table :employees do |t|
536
      t.references :manager, index: true
537
      t.timestamps
538 539 540 541 542
    end
  end
end
```

543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
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
* Bi-directional associations

### Controlling Caching

All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:

```ruby
559 560 561
author.books                 # retrieves books from the database
author.books.size            # uses the cached copy of books
author.books.empty?          # uses the cached copy of books
562 563
```

564
But what if you want to reload the cache, because data might have been changed by some other part of the application? Just call `reload` on the association:
565 566

```ruby
567 568
author.books                 # retrieves books from the database
author.books.size            # uses the cached copy of books
N
Neodelf 已提交
569 570
author.books.reload.empty?   # discards the cached copy of books
                             # and goes back to the database
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
```

### Avoiding Name Collisions

You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of `ActiveRecord::Base`. The association method would override the base method and break things. For instance, `attributes` or `connection` are bad names for associations.

### Updating the Schema

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

#### Creating Foreign Keys for `belongs_to` Associations

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

```ruby
586 587
class Book < ApplicationRecord
  belongs_to :author
588 589 590
end
```

591
This declaration needs to be backed up by a corresponding foreign key column in the books table. For a brand new table, the migration might look something like this:
592 593

```ruby
594
class CreateBooks < ActiveRecord::Migration[5.0]
595
  def change
596
    create_table :books do |t|
597 598 599
      t.datetime   :published_at
      t.string     :book_number
      t.references :author
600 601 602 603 604
    end
  end
end
```

605
Whereas for an existing table, it might look like this:
606 607

```ruby
608
class AddAuthorToBooks < ActiveRecord::Migration[5.0]
609
  def change
610
    add_reference :books, :author
611 612 613 614
  end
end
```

615 616
NOTE: If you wish to [enforce referential integrity at the database level](/active_record_migrations.html#foreign-keys), add the `foreign_key: true` option to the ‘reference’ column declarations above.

617 618
#### Creating Join Tables for `has_and_belongs_to_many` Associations

619
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 book of the class names. So a join between author and book models will give the default join table name of "authors_books" because "a" outranks "b" in lexical ordering.
620

621
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" (because the underscore '\_' is lexicographically _less_ than 's' in common encodings).
622 623 624 625

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

```ruby
626
class Assembly < ApplicationRecord
627 628 629
  has_and_belongs_to_many :parts
end

630
class Part < ApplicationRecord
631 632 633 634 635 636 637
  has_and_belongs_to_many :assemblies
end
```

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
638
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[5.0]
639
  def change
640
    create_table :assemblies_parts, id: false do |t|
641 642 643
      t.integer :assembly_id
      t.integer :part_id
    end
644 645 646

    add_index :assemblies_parts, :assembly_id
    add_index :assemblies_parts, :part_id
647 648 649 650
  end
end
```

651
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 behavior in a `has_and_belongs_to_many` association like mangled model IDs, or exceptions about conflicting IDs, chances are you forgot that bit.
652

653 654 655
You can also use the method `create_join_table`

```ruby
656
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[5.0]
657 658 659 660 661 662 663 664 665
  def change
    create_join_table :assemblies, :parts do |t|
      t.index :assembly_id
      t.index :part_id
    end
  end
end
```

666 667 668 669 670 671 672
### Controlling Association Scope

By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:

```ruby
module MyApplication
  module Business
673
    class Supplier < ApplicationRecord
Y
Yauheni Dakuka 已提交
674
      has_one :account
675 676
    end

677
    class Account < ApplicationRecord
Y
Yauheni Dakuka 已提交
678
      belongs_to :supplier
679 680 681 682 683 684 685 686 687 688
    end
  end
end
```

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:

```ruby
module MyApplication
  module Business
689
    class Supplier < ApplicationRecord
Y
Yauheni Dakuka 已提交
690
      has_one :account
691 692 693 694
    end
  end

  module Billing
695
    class Account < ApplicationRecord
Y
Yauheni Dakuka 已提交
696
      belongs_to :supplier
697 698 699 700 701 702 703 704 705 706
    end
  end
end
```

To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:

```ruby
module MyApplication
  module Business
707
    class Supplier < ApplicationRecord
Y
Yauheni Dakuka 已提交
708
      has_one :account,
709
        class_name: "MyApplication::Billing::Account"
710 711 712 713
    end
  end

  module Billing
714
    class Account < ApplicationRecord
Y
Yauheni Dakuka 已提交
715
      belongs_to :supplier,
716
        class_name: "MyApplication::Business::Supplier"
717 718 719 720 721 722 723 724 725 726
    end
  end
end
```

### Bi-directional Associations

It's normal for associations to work in two directions, requiring declaration on two different models:

```ruby
727 728
class Author < ApplicationRecord
  has_many :books
729 730
end

731 732
class Book < ApplicationRecord
  belongs_to :author
733 734 735
end
```

736
Active Record will attempt to automatically identify that these two models share a bi-directional association based on the association name. In this way, Active Record will only load one copy of the `Author` object, making your application more efficient and preventing inconsistent data:
737 738

```ruby
739
a = Author.first
M
Mikhail Dieterle 已提交
740
b = a.books.first
741
a.first_name == b.author.first_name # => true
742 743
a.first_name = 'David'
a.first_name == b.author.first_name # => true
744 745
```

746
Active Record supports automatic identification for most associations with standard names. However, Active Record will not automatically identify bi-directional associations that contain a scope or any of the following options:
747 748 749 750 751

* `:through`
* `:foreign_key`

For example, consider the following model declarations:
752 753

```ruby
754
class Author < ApplicationRecord
755
  has_many :books
756 757
end

M
Mikhail Dieterle 已提交
758
class Book < ApplicationRecord
759
  belongs_to :writer, class_name: 'Author', foreign_key: 'author_id'
760 761 762
end
```

763
Active Record will no longer automatically recognize the bi-directional association:
764 765

```ruby
M
Mikhail Dieterle 已提交
766 767
a = Author.first
b = a.books.first
768 769 770
a.first_name == b.writer.first_name # => true
a.first_name = 'David'
a.first_name == b.writer.first_name # => false
771 772
```

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
Active Record provides the `:inverse_of` option so you can explicitly declare bi-directional associations:

```ruby
class Author < ApplicationRecord
  has_many :books, inverse_of: 'writer'
end

class Book < ApplicationRecord
  belongs_to :writer, class_name: 'Author', foreign_key: 'author_id'
end
```

By including the `:inverse_of` option in the `has_many` association declaration, Active Record will now recognize the bi-directional association:

```ruby
a = Author.first
b = a.books.first
a.first_name == b.writer.first_name # => true
a.first_name = 'David'
a.first_name == b.writer.first_name # => true
```

795 796 797 798 799 800 801 802 803 804 805
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.

### `belongs_to` Association Reference

The `belongs_to` association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use `has_one` instead.

#### Methods Added by `belongs_to`

T
Tom Copeland 已提交
806
When you declare a `belongs_to` association, the declaring class automatically gains 6 methods related to the association:
807

808
* `association`
809 810 811
* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
812
* `create_association!(attributes = {})`
813
* `reload_association`
814 815 816 817

In all of these methods, `association` is replaced with the symbol passed as the first argument to `belongs_to`. For example, given the declaration:

```ruby
818 819
class Book < ApplicationRecord
  belongs_to :author
820 821 822
end
```

823
Each instance of the `Book` model will have these methods:
824 825

```ruby
826 827 828 829 830
author
author=
build_author
create_author
create_author!
831
reload_author
832 833 834 835
```

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.

836
##### `association`
837 838 839 840

The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.

```ruby
841
@author = @book.author
842 843
```

844
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), call `#reload_association` on the parent object.
845 846

```ruby
847
@author = @book.reload_author
848
```
849 850 851

##### `association=(associate)`

852
The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associated object and setting this object's foreign key to the same value.
853 854

```ruby
855
@book.author = @author
856 857 858 859 860 861 862
```

##### `build_association(attributes = {})`

The `build_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.

```ruby
863 864
@author = @book.build_author(author_number: 123,
                                  author_name: "John Doe")
865 866 867 868 869 870 871
```

##### `create_association(attributes = {})`

The `create_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.

```ruby
872 873
@author = @book.create_author(author_number: 123,
                                   author_name: "John Doe")
874 875
```

876 877
##### `create_association!(attributes = {})`

878
Does the same as `create_association` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid.
879

880 881 882

#### Options for `belongs_to`

883
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `belongs_to` association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this association uses two such options:
884 885

```ruby
886 887
class Book < ApplicationRecord
  belongs_to :author, dependent: :destroy,
888
    counter_cache: true
889 890 891 892 893 894 895 896 897 898
end
```

The `belongs_to` association supports these options:

* `:autosave`
* `:class_name`
* `:counter_cache`
* `:dependent`
* `:foreign_key`
899
* `:primary_key`
900 901 902 903
* `:inverse_of`
* `:polymorphic`
* `:touch`
* `:validate`
904
* `:optional`
905 906 907

##### `:autosave`

908
If you set the `:autosave` option to `true`, Rails will save any loaded association members and destroy members that are marked for destruction whenever you save the parent object. Setting `:autosave` to `false` is not the same as not setting the `:autosave` option. If the `:autosave` option is not present, then new associated objects will be saved, but updated associated objects will not be saved.
909 910 911

##### `:class_name`

912
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 book belongs to an author, but the actual name of the model containing authors is `Patron`, you'd set things up this way:
913 914

```ruby
915 916
class Book < ApplicationRecord
  belongs_to :author, class_name: "Patron"
917 918 919 920 921 922 923 924
end
```

##### `:counter_cache`

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

```ruby
925 926
class Book < ApplicationRecord
  belongs_to :author
927
end
928 929
class Author < ApplicationRecord
  has_many :books
930 931 932
end
```

933
With these declarations, asking for the value of `@author.books.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:
934 935

```ruby
936 937
class Book < ApplicationRecord
  belongs_to :author, counter_cache: true
938
end
939 940
class Author < ApplicationRecord
  has_many :books
941 942 943 944 945
end
```

With this declaration, Rails will keep the cache value up to date, and then return that value in response to the `size` method.

946 947 948
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_ (`has_many`) model. In the case above, you would need to add a
949
column named `books_count` to the `Author` model.
950 951 952

You can override the default column name by specifying a custom column name in
the `counter_cache` declaration instead of `true`. For example, to use
953
`count_of_books` instead of `books_count`:
954 955

```ruby
956 957
class Book < ApplicationRecord
  belongs_to :author, counter_cache: :count_of_books
958
end
959 960
class Author < ApplicationRecord
  has_many :books
961 962 963
end
```

964
NOTE: You only need to specify the `:counter_cache` option on the `belongs_to`
965
side of the association.
966

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

##### `:dependent`
970
If you set the `:dependent` option to:
971

972 973 974 975
* `:destroy`, when the object is destroyed, `destroy` will be called on its
associated objects.
* `:delete`, when the object is destroyed, all its associated objects will be
deleted directly from the database without calling their `destroy` method.
976 977 978 979 980 981 982 983

WARNING: You should not specify this option on a `belongs_to` association that is connected with a `has_many` association on the other class. Doing so can lead to orphaned records in your database.

##### `:foreign_key`

By convention, Rails assumes 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
984 985
class Book < ApplicationRecord
  belongs_to :author, class_name: "Patron",
986
                        foreign_key: "patron_id"
987 988 989 990 991
end
```

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

992 993
##### `:primary_key`

994 995
By convention, Rails assumes that the `id` column is used to hold the primary key
of its tables. The `:primary_key` option allows you to specify a different column.
996

997
For example, given we have a `users` table with `guid` as the primary key. If we want a separate `todos` table to hold the foreign key `user_id` in the `guid` column, then we can use `primary_key` to achieve this like so:
998 999

```ruby
1000
class User < ApplicationRecord
J
Jon Atack 已提交
1001
  self.primary_key = 'guid' # primary key is guid and not id
1002 1003
end

1004
class Todo < ApplicationRecord
1005 1006 1007 1008
  belongs_to :user, primary_key: 'guid'
end
```

1009 1010
When we execute `@user.todos.create` then the `@todo` record will have its
`user_id` value as the `guid` value of `@user`.
1011

1012 1013
##### `:inverse_of`

1014
The `:inverse_of` option specifies the name of the `has_many` or `has_one` association that is the inverse of this association.
1015 1016

```ruby
1017 1018
class Author < ApplicationRecord
  has_many :books, inverse_of: :author
1019 1020
end

1021 1022
class Book < ApplicationRecord
  belongs_to :author, inverse_of: :books
1023 1024 1025 1026 1027 1028 1029 1030 1031
end
```

##### `:polymorphic`

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

##### `:touch`

1032
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:
1033 1034

```ruby
1035 1036
class Book < ApplicationRecord
  belongs_to :author, touch: true
1037 1038
end

1039 1040
class Author < ApplicationRecord
  has_many :books
1041 1042 1043
end
```

W
Waitaya Krongapiradee 已提交
1044
In this case, saving or destroying a book will update the timestamp on the associated author. You can also specify a particular timestamp attribute to update:
1045 1046

```ruby
1047 1048
class Book < ApplicationRecord
  belongs_to :author, touch: :books_updated_at
1049 1050 1051 1052 1053 1054 1055
end
```

##### `:validate`

If you set the `:validate` option to `true`, then associated objects will be validated whenever you save this object. By default, this is `false`: associated objects will not be validated when this object is saved.

1056 1057
##### `:optional`

1058 1059
If you set the `:optional` option to `true`, then the presence of the associated
object won't be validated. By default, this option is set to `false`.
1060

1061 1062 1063 1064 1065
#### Scopes for `belongs_to`

There may be times when you wish to customize the query used by `belongs_to`. Such customizations can be achieved via a scope block. For example:

```ruby
1066 1067
class Book < ApplicationRecord
  belongs_to :author, -> { where active: true },
1068
                        dependent: :destroy
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
end
```

You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:

* `where`
* `includes`
* `readonly`
* `select`

##### `where`

The `where` method lets you specify the conditions that the associated object must meet.

```ruby
1084
class Book < ApplicationRecord
1085
  belongs_to :author, -> { where active: true }
1086 1087 1088 1089 1090
end
```

##### `includes`

1091
You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
1092 1093

```ruby
1094
class LineItem < ApplicationRecord
1095
  belongs_to :book
1096 1097
end

1098 1099
class Book < ApplicationRecord
  belongs_to :author
1100 1101 1102
  has_many :line_items
end

1103 1104
class Author < ApplicationRecord
  has_many :books
1105 1106 1107
end
```

1108
If you frequently retrieve authors directly from line items (`@line_item.book.author`), then you can make your code somewhat more efficient by including authors in the association from line items to books:
1109 1110

```ruby
1111
class LineItem < ApplicationRecord
1112
  belongs_to :book, -> { includes :author }
1113 1114
end

1115 1116
class Book < ApplicationRecord
  belongs_to :author
1117 1118 1119
  has_many :line_items
end

1120 1121
class Author < ApplicationRecord
  has_many :books
1122 1123 1124
end
```

1125
NOTE: There's no need to use `includes` for immediate associations - that is, if you have `Book belongs_to :author`, then the author is eager-loaded automatically when it's needed.
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141

##### `readonly`

If you use `readonly`, then the associated object will be read-only when retrieved via the association.

##### `select`

The `select` method 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 use the `select` method on a `belongs_to` association, you should also set the `:foreign_key` option to guarantee the correct results.

#### Do Any Associated Objects Exist?

You can see if any associated objects exist by using the `association.nil?` method:

```ruby
1142 1143
if @book.author.nil?
  @msg = "No author found for this book"
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
end
```

#### When are Objects Saved?

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

### `has_one` Association Reference

The `has_one` association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use `belongs_to` instead.

#### Methods Added by `has_one`

T
Tom Copeland 已提交
1157
When you declare a `has_one` association, the declaring class automatically gains 6 methods related to the association:
1158

1159
* `association`
1160 1161 1162
* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
1163
* `create_association!(attributes = {})`
1164
* `reload_association`
1165 1166 1167 1168

In all of these methods, `association` is replaced with the symbol passed as the first argument to `has_one`. For example, given the declaration:

```ruby
1169
class Supplier < ApplicationRecord
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
  has_one :account
end
```

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

```ruby
account
account=
build_account
create_account
1181
create_account!
1182
reload_account
1183 1184 1185 1186
```

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.

1187
##### `association`
1188 1189 1190 1191 1192 1193 1194

The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.

```ruby
@account = @supplier.account
```

1195
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), call `#reload_association` on the parent object.
1196 1197

```ruby
1198
@account = @supplier.reload_account
1199
```
1200 1201 1202

##### `association=(associate)`

1203
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 associated object's foreign key to the same value.
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213

```ruby
@supplier.account = @account
```

##### `build_association(attributes = {})`

The `build_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.

```ruby
1214
@account = @supplier.build_account(terms: "Net 30")
1215 1216 1217 1218 1219 1220 1221
```

##### `create_association(attributes = {})`

The `create_association` 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 set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.

```ruby
1222
@account = @supplier.create_account(terms: "Net 30")
1223 1224
```

1225 1226
##### `create_association!(attributes = {})`

1227
Does the same as `create_association` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid.
1228

1229 1230
#### Options for `has_one`

1231
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_one` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
1232 1233

```ruby
1234
class Supplier < ApplicationRecord
1235
  has_one :account, class_name: "Billing", dependent: :nullify
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
end
```

The `has_one` association supports these options:

* `:as`
* `:autosave`
* `:class_name`
* `:dependent`
* `:foreign_key`
* `:inverse_of`
* `:primary_key`
* `:source`
* `:source_type`
* `:through`
* `:validate`

##### `:as`

N
Nishant Modak 已提交
1255
Setting the `:as` option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail [earlier in this guide](#polymorphic-associations).
1256 1257 1258

##### `:autosave`

1259
If you set the `:autosave` option to `true`, Rails will save any loaded association members and destroy members that are marked for destruction whenever you save the parent object. Setting `:autosave` to `false` is not the same as not setting the `:autosave` option. If the `:autosave` option is not present, then new associated objects will be saved, but updated associated objects will not be saved.
1260 1261 1262 1263 1264 1265

##### `:class_name`

If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is `Billing`, you'd set things up this way:

```ruby
1266
class Supplier < ApplicationRecord
1267
  has_one :account, class_name: "Billing"
1268 1269 1270 1271 1272 1273 1274 1275
end
```

##### `:dependent`

Controls what happens to the associated object when its owner is destroyed:

* `:destroy` causes the associated object to also be destroyed
A
Typppo  
Akira Matsuda 已提交
1276
* `:delete` causes the associated object to be deleted directly from the database (so callbacks will not execute)
1277 1278 1279 1280
* `:nullify` causes the foreign key to be set to `NULL`. Callbacks are not executed.
* `:restrict_with_exception` causes an exception to be raised if there is an associated record
* `:restrict_with_error` causes an error to be added to the owner if there is an associated object

1281 1282 1283
It's necessary not to set or leave `:nullify` option for those associations
that have `NOT NULL` database constraints. If you don't set `dependent` to
destroy such associations you won't be able to change the associated object
1284 1285
because the initial associated object's foreign key will be set to the
unallowed `NULL` value.
1286

1287 1288 1289 1290 1291
##### `:foreign_key`

By convention, Rails assumes 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
1292
class Supplier < ApplicationRecord
1293
  has_one :account, foreign_key: "supp_id"
1294 1295 1296 1297 1298 1299 1300
end
```

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

##### `:inverse_of`

1301
The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association.
1302 1303

```ruby
1304
class Supplier < ApplicationRecord
1305
  has_one :account, inverse_of: :supplier
1306 1307
end

1308
class Account < ApplicationRecord
1309
  belongs_to :supplier, inverse_of: :account
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
end
```

##### `:primary_key`

By convention, Rails assumes 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.

##### `:source`

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

##### `:source_type`

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

##### `:through`

N
Nishant Modak 已提交
1327
The `:through` option specifies a join model through which to perform the query. `has_one :through` associations were discussed in detail [earlier in this guide](#the-has-one-through-association).
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337

##### `:validate`

If you set the `:validate` option to `true`, then associated objects will be validated whenever you save this object. By default, this is `false`: associated objects will not be validated when this object is saved.

#### Scopes for `has_one`

There may be times when you wish to customize the query used by `has_one`. Such customizations can be achieved via a scope block. For example:

```ruby
1338
class Supplier < ApplicationRecord
1339
  has_one :account, -> { where active: true }
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
end
```

You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:

* `where`
* `includes`
* `readonly`
* `select`

##### `where`

The `where` method lets you specify the conditions that the associated object must meet.

```ruby
1355
class Supplier < ApplicationRecord
1356 1357 1358 1359 1360 1361 1362 1363 1364
  has_one :account, -> { where "confirmed = 1" }
end
```

##### `includes`

You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:

```ruby
1365
class Supplier < ApplicationRecord
1366 1367 1368
  has_one :account
end

1369
class Account < ApplicationRecord
1370 1371 1372 1373
  belongs_to :supplier
  belongs_to :representative
end

1374
class Representative < ApplicationRecord
1375 1376 1377 1378 1379 1380 1381
  has_many :accounts
end
```

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
1382
class Supplier < ApplicationRecord
1383 1384 1385
  has_one :account, -> { includes :representative }
end

1386
class Account < ApplicationRecord
1387 1388 1389 1390
  belongs_to :supplier
  belongs_to :representative
end

1391
class Representative < ApplicationRecord
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
  has_many :accounts
end
```

##### `readonly`

If you use the `readonly` method, then the associated object will be read-only when retrieved via the association.

##### `select`

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

#### Do Any Associated Objects Exist?

You can see if any associated objects exist by using the `association.nil?` method:

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

#### When are Objects Saved?

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

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

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

W
willnet 已提交
1422
If you want to assign an object to a `has_one` association without saving the object, use the `build_association` method.
1423 1424 1425 1426 1427 1428 1429

### `has_many` Association Reference

The `has_many` association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.

#### Methods Added by `has_many`

T
Tom Copeland 已提交
1430
When you declare a `has_many` association, the declaring class automatically gains 17 methods related to the association:
1431

1432
* `collection`
1433 1434 1435
* `collection<<(object, ...)`
* `collection.delete(object, ...)`
* `collection.destroy(object, ...)`
1436
* `collection=(objects)`
1437
* `collection_singular_ids`
1438
* `collection_singular_ids=(ids)`
1439 1440 1441 1442 1443 1444 1445 1446
* `collection.clear`
* `collection.empty?`
* `collection.size`
* `collection.find(...)`
* `collection.where(...)`
* `collection.exists?(...)`
* `collection.build(attributes = {}, ...)`
* `collection.create(attributes = {})`
1447
* `collection.create!(attributes = {})`
1448
* `collection.reload`
1449

1450
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:
1451 1452

```ruby
1453 1454
class Author < ApplicationRecord
  has_many :books
1455 1456 1457
end
```

1458
Each instance of the `Author` model will have these methods:
1459 1460

```ruby
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
books
books<<(object, ...)
books.delete(object, ...)
books.destroy(object, ...)
books=(objects)
book_ids
book_ids=(ids)
books.clear
books.empty?
books.size
books.find(...)
books.where(...)
books.exists?(...)
books.build(attributes = {}, ...)
books.create(attributes = {})
books.create!(attributes = {})
1477
books.reload
1478 1479
```

1480
##### `collection`
1481

1482
The `collection` method returns a Relation of all of the associated objects. If there are no associated objects, it returns an empty Relation.
1483 1484

```ruby
1485
@books = @author.books
1486 1487 1488 1489 1490 1491 1492
```

##### `collection<<(object, ...)`

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

```ruby
1493
@author.books << @book1
1494 1495 1496 1497 1498 1499 1500
```

##### `collection.delete(object, ...)`

The `collection.delete` method removes one or more objects from the collection by setting their foreign keys to `NULL`.

```ruby
1501
@author.books.delete(@book1)
1502 1503
```

1504
WARNING: Additionally, objects will be destroyed if they're associated with `dependent: :destroy`, and deleted if they're associated with `dependent: :delete_all`.
1505 1506 1507 1508 1509 1510

##### `collection.destroy(object, ...)`

The `collection.destroy` method removes one or more objects from the collection by running `destroy` on each object.

```ruby
1511
@author.books.destroy(@book1)
1512 1513 1514 1515
```

WARNING: Objects will _always_ be removed from the database, ignoring the `:dependent` option.

1516
##### `collection=(objects)`
1517

1518
The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate. The changes are persisted to the database.
1519 1520 1521 1522 1523 1524

##### `collection_singular_ids`

The `collection_singular_ids` method returns an array of the ids of the objects in the collection.

```ruby
1525
@book_ids = @author.book_ids
1526 1527
```

1528
##### `collection_singular_ids=(ids)`
1529

1530
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. The changes are persisted to the database.
1531 1532 1533

##### `collection.clear`

1534 1535 1536
The `collection.clear` method removes all objects from the collection according to the strategy specified by the `dependent` option. If no option is given, it follows the default strategy. The default strategy for `has_many :through` associations is `delete_all`, and for `has_many` associations is to set the foreign keys to `NULL`.

```ruby
1537
@author.books.clear
1538 1539
```

1540 1541
WARNING: Objects will be deleted if they're associated with `dependent: :destroy`,
just like `dependent: :delete_all`.
1542 1543 1544 1545 1546 1547

##### `collection.empty?`

The `collection.empty?` method returns `true` if the collection does not contain any associated objects.

```erb
1548 1549
<% if @author.books.empty? %>
  No Books Found
1550 1551 1552 1553 1554 1555 1556 1557
<% end %>
```

##### `collection.size`

The `collection.size` method returns the number of objects in the collection.

```ruby
1558
@book_count = @author.books.size
1559 1560 1561 1562
```

##### `collection.find(...)`

1563 1564
The `collection.find` method finds objects within the collection. It uses the same syntax and options as
[`ActiveRecord::Base.find`](http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find).
1565 1566

```ruby
1567
@available_book = @author.books.find(1)
1568 1569 1570 1571 1572 1573 1574
```

##### `collection.where(...)`

The `collection.where` 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
1575 1576
@available_books = @author.books.where(available: true) # No query yet
@available_book = @available_books.first # Now the database will be queried
1577 1578 1579 1580
```

##### `collection.exists?(...)`

1581
The `collection.exists?` method checks whether an object meeting the supplied
1582 1583
conditions exists in the collection. It uses the same syntax and options as
[`ActiveRecord::Base.exists?`](http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F).
1584 1585 1586

##### `collection.build(attributes = {}, ...)`

1587
The `collection.build` method returns a single or array of new objects of the associated type. The object(s) 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.
1588 1589

```ruby
1590 1591
@book = @author.books.build(published_at: Time.now,
                                book_number: "A12345")
1592

1593 1594 1595
@books = @author.books.build([
  { published_at: Time.now, book_number: "A12346" },
  { published_at: Time.now, book_number: "A12347" }
1596
])
1597 1598 1599 1600
```

##### `collection.create(attributes = {})`

1601
The `collection.create` method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
1602 1603

```ruby
1604 1605
@book = @author.books.create(published_at: Time.now,
                                 book_number: "A12345")
1606

1607 1608 1609
@books = @author.books.create([
  { published_at: Time.now, book_number: "A12346" },
  { published_at: Time.now, book_number: "A12347" }
1610
])
1611 1612
```

1613 1614
##### `collection.create!(attributes = {})`

1615
Does the same as `collection.create` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid.
1616

1617 1618 1619 1620 1621 1622 1623 1624
##### `collection.reload`

The `collection.reload` method returns a Relation of all of the associated objects, forcing a database read. If there are no associated objects, it returns an empty Relation.

```ruby
@books = @author.books.reload
```

1625 1626
#### Options for `has_many`

1627
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_many` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
1628 1629

```ruby
1630 1631
class Author < ApplicationRecord
  has_many :books, dependent: :delete_all, validate: false
1632 1633 1634 1635 1636 1637 1638 1639
end
```

The `has_many` association supports these options:

* `:as`
* `:autosave`
* `:class_name`
1640
* `:counter_cache`
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
* `:dependent`
* `:foreign_key`
* `:inverse_of`
* `:primary_key`
* `:source`
* `:source_type`
* `:through`
* `:validate`

##### `:as`

N
Nishant Modak 已提交
1652
Setting the `:as` option indicates that this is a polymorphic association, as discussed [earlier in this guide](#polymorphic-associations).
1653 1654 1655

##### `:autosave`

1656
If you set the `:autosave` option to `true`, Rails will save any loaded association members and destroy members that are marked for destruction whenever you save the parent object. Setting `:autosave` to `false` is not the same as not setting the `:autosave` option. If the `:autosave` option is not present, then new associated objects will be saved, but updated associated objects will not be saved.
1657 1658 1659

##### `:class_name`

1660
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 author has many books, but the actual name of the model containing books is `Transaction`, you'd set things up this way:
1661 1662

```ruby
1663 1664
class Author < ApplicationRecord
  has_many :books, class_name: "Transaction"
1665 1666 1667
end
```

1668
##### `:counter_cache`
R
Robin Dupret 已提交
1669

1670 1671
This option can be used to configure a custom named `:counter_cache`. You only need this option when you customized the name of your `:counter_cache` on the [belongs_to association](#options-for-belongs-to).

1672 1673 1674 1675 1676
##### `:dependent`

Controls what happens to the associated objects when their owner is destroyed:

* `:destroy` causes all the associated objects to also be destroyed
A
Typppo  
Akira Matsuda 已提交
1677
* `:delete_all` causes all the associated objects to be deleted directly from the database (so callbacks will not execute)
1678 1679 1680 1681 1682 1683 1684 1685 1686
* `:nullify` causes the foreign keys to be set to `NULL`. Callbacks are not executed.
* `:restrict_with_exception` causes an exception to be raised if there are any associated records
* `:restrict_with_error` causes an error to be added to the owner if there are any associated objects

##### `:foreign_key`

By convention, Rails assumes 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
1687 1688
class Author < ApplicationRecord
  has_many :books, foreign_key: "cust_id"
1689 1690 1691 1692 1693 1694 1695
end
```

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

##### `:inverse_of`

1696
The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association.
1697 1698

```ruby
1699 1700
class Author < ApplicationRecord
  has_many :books, inverse_of: :author
1701 1702
end

1703 1704
class Book < ApplicationRecord
  belongs_to :author, inverse_of: :books
1705 1706 1707 1708 1709 1710 1711
end
```

##### `:primary_key`

By convention, Rails assumes 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.

1712 1713 1714 1715
Let's say the `users` table has `id` as the primary_key but it also
has a `guid` column. The requirement is that the `todos` table should
hold the `guid` column value as the foreign key and not `id`
value. This can be achieved like this:
1716 1717

```ruby
1718
class User < ApplicationRecord
1719 1720 1721 1722
  has_many :todos, primary_key: :guid
end
```

1723 1724
Now if we execute `@todo = @user.todos.create` then the `@todo`
record's `user_id` value will be the `guid` value of `@user`.
1725 1726


1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
##### `:source`

The `:source` option specifies the source association name for a `has_many :through` association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.

##### `:source_type`

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

##### `:through`

N
Nishant Modak 已提交
1737
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](#the-has-many-through-association).
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747

##### `:validate`

If you set the `:validate` option to `false`, then associated objects will not be validated whenever you save this object. By default, this is `true`: associated objects will be validated when this object is saved.

#### Scopes for `has_many`

There may be times when you wish to customize the query used by `has_many`. Such customizations can be achieved via a scope block. For example:

```ruby
1748 1749
class Author < ApplicationRecord
  has_many :books, -> { where processed: true }
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
end
```

You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:

* `where`
* `extending`
* `group`
* `includes`
* `limit`
* `offset`
* `order`
* `readonly`
* `select`
M
Markov Alexey 已提交
1764
* `distinct`
1765 1766 1767 1768 1769 1770

##### `where`

The `where` method lets you specify the conditions that the associated object must meet.

```ruby
1771 1772 1773
class Author < ApplicationRecord
  has_many :confirmed_books, -> { where "confirmed = 1" },
    class_name: "Book"
1774 1775 1776 1777 1778 1779
end
```

You can also set conditions via a hash:

```ruby
1780 1781 1782
class Author < ApplicationRecord
  has_many :confirmed_books, -> { where confirmed: true },
                              class_name: "Book"
1783 1784 1785
end
```

1786
If you use a hash-style `where` option, then record creation via this association will be automatically scoped using the hash. In this case, using `@author.confirmed_books.create` or `@author.confirmed_books.build` will create books where the confirmed column has the value `true`.
1787 1788 1789

##### `extending`

N
Nishant Modak 已提交
1790
The `extending` method specifies a named module to extend the association proxy. Association extensions are discussed in detail [later in this guide](#association-extensions).
1791 1792 1793 1794 1795 1796

##### `group`

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

```ruby
1797 1798 1799
class Author < ApplicationRecord
  has_many :line_items, -> { group 'books.id' },
                        through: :books
1800 1801 1802 1803 1804 1805 1806 1807
end
```

##### `includes`

You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:

```ruby
1808 1809
class Author < ApplicationRecord
  has_many :books
1810 1811
end

1812 1813
class Book < ApplicationRecord
  belongs_to :author
1814 1815 1816
  has_many :line_items
end

1817
class LineItem < ApplicationRecord
1818
  belongs_to :book
1819 1820 1821
end
```

1822
If you frequently retrieve line items directly from authors (`@author.books.line_items`), then you can make your code somewhat more efficient by including line items in the association from authors to books:
1823 1824

```ruby
1825 1826
class Author < ApplicationRecord
  has_many :books, -> { includes :line_items }
1827 1828
end

1829 1830
class Book < ApplicationRecord
  belongs_to :author
1831 1832 1833
  has_many :line_items
end

1834
class LineItem < ApplicationRecord
1835
  belongs_to :book
1836 1837 1838 1839 1840 1841 1842 1843
end
```

##### `limit`

The `limit` method lets you restrict the total number of objects that will be fetched through an association.

```ruby
1844 1845 1846
class Author < ApplicationRecord
  has_many :recent_books,
    -> { order('published_at desc').limit(100) },
1847
    class_name: "Book"
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
end
```

##### `offset`

The `offset` method lets you specify the starting offset for fetching objects via an association. For example, `-> { offset(11) }` will skip the first 11 records.

##### `order`

The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).

```ruby
1860 1861
class Author < ApplicationRecord
  has_many :books, -> { order "date_confirmed DESC" }
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
end
```

##### `readonly`

If you use the `readonly` method, then the associated objects will be read-only when retrieved via the association.

##### `select`

The `select` method 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.

1875
##### `distinct`
1876

1877 1878
Use the `distinct` method to keep the collection free of duplicates. This is
mostly useful together with the `:through` option.
1879 1880

```ruby
1881
class Person < ApplicationRecord
1882
  has_many :readings
1883
  has_many :articles, through: :readings
1884 1885
end

1886
person = Person.create(name: 'John')
1887 1888 1889 1890
article   = Article.create(name: 'a1')
person.articles << article
person.articles << article
person.articles.inspect # => [#<Article id: 5, name: "a1">, #<Article id: 5, name: "a1">]
N
Neodelf 已提交
1891
Reading.all.inspect     # => [#<Reading id: 12, person_id: 5, article_id: 5>, #<Reading id: 13, person_id: 5, article_id: 5>]
1892 1893
```

1894 1895
In the above case there are two readings and `person.articles` brings out both of
them even though these records are pointing to the same article.
1896

1897
Now let's set `distinct`:
1898 1899 1900 1901

```ruby
class Person
  has_many :readings
1902
  has_many :articles, -> { distinct }, through: :readings
1903 1904
end

1905
person = Person.create(name: 'Honda')
1906 1907 1908 1909
article   = Article.create(name: 'a1')
person.articles << article
person.articles << article
person.articles.inspect # => [#<Article id: 7, name: "a1">]
N
Neodelf 已提交
1910
Reading.all.inspect     # => [#<Reading id: 16, person_id: 7, article_id: 7>, #<Reading id: 17, person_id: 7, article_id: 7>]
1911 1912
```

1913 1914
In the above case there are still two readings. However `person.articles` shows
only one article because the collection loads only unique records.
1915

S
Sunny Ripert 已提交
1916 1917 1918 1919
If you want to make sure that, upon insertion, all of the records in the
persisted association are distinct (so that you can be sure that when you
inspect the association that you will never find duplicate records), you should
add a unique index on the table itself. For example, if you have a table named
1920 1921
`readings` and you want to make sure the articles can only be added to a person once,
you could add the following in a migration:
1922 1923

```ruby
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
add_index :readings, [:person_id, :article_id], unique: true
```

Once you have this unique index, attempting to add the article to a person twice
will raise an `ActiveRecord::RecordNotUnique` error:

```ruby
person = Person.create(name: 'Honda')
article = Article.create(name: 'a1')
person.articles << article
person.articles << article # => ActiveRecord::RecordNotUnique
1935 1936
```

1937 1938
Note that checking for uniqueness using something like `include?` is subject
to race conditions. Do not attempt to use `include?` to enforce distinctness
1939
in an association. For instance, using the article example from above, the
S
Sunny Ripert 已提交
1940
following code would be racy because multiple users could be attempting this
1941 1942 1943
at the same time:

```ruby
1944
person.articles << article unless person.articles.include?(article)
1945
```
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962

#### When are Objects Saved?

When you assign an object to a `has_many` association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.

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 `collection.build` method.

### `has_and_belongs_to_many` Association Reference

The `has_and_belongs_to_many` association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.

#### Methods Added by `has_and_belongs_to_many`

T
Tom Copeland 已提交
1963
When you declare a `has_and_belongs_to_many` association, the declaring class automatically gains 17 methods related to the association:
1964

1965
* `collection`
1966 1967 1968
* `collection<<(object, ...)`
* `collection.delete(object, ...)`
* `collection.destroy(object, ...)`
1969
* `collection=(objects)`
1970
* `collection_singular_ids`
1971
* `collection_singular_ids=(ids)`
1972 1973 1974 1975 1976 1977 1978 1979
* `collection.clear`
* `collection.empty?`
* `collection.size`
* `collection.find(...)`
* `collection.where(...)`
* `collection.exists?(...)`
* `collection.build(attributes = {})`
* `collection.create(attributes = {})`
1980
* `collection.create!(attributes = {})`
1981
* `collection.reload`
1982 1983 1984 1985

In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_and_belongs_to_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:

```ruby
1986
class Part < ApplicationRecord
1987 1988 1989 1990
  has_and_belongs_to_many :assemblies
end
```

1991
Each instance of the `Part` model will have these methods:
1992 1993

```ruby
1994
assemblies
1995 1996 1997
assemblies<<(object, ...)
assemblies.delete(object, ...)
assemblies.destroy(object, ...)
1998
assemblies=(objects)
1999
assembly_ids
2000
assembly_ids=(ids)
2001 2002 2003 2004 2005 2006 2007 2008
assemblies.clear
assemblies.empty?
assemblies.size
assemblies.find(...)
assemblies.where(...)
assemblies.exists?(...)
assemblies.build(attributes = {}, ...)
assemblies.create(attributes = {})
2009
assemblies.create!(attributes = {})
2010
assemblies.reload
2011 2012 2013 2014 2015 2016 2017 2018 2019
```

##### Additional Column Methods

If the join table for a `has_and_belongs_to_many` association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.

WARNING: The use of extra attributes on the join table in a `has_and_belongs_to_many` association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a `has_many :through` association instead of `has_and_belongs_to_many`.


2020
##### `collection`
2021

2022
The `collection` method returns a Relation of all of the associated objects. If there are no associated objects, it returns an empty Relation.
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047

```ruby
@assemblies = @part.assemblies
```

##### `collection<<(object, ...)`

The `collection<<` method adds one or more objects to the collection by creating records in the join table.

```ruby
@part.assemblies << @assembly1
```

NOTE: This method is aliased as `collection.concat` and `collection.push`.

##### `collection.delete(object, ...)`

The `collection.delete` method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.

```ruby
@part.assemblies.delete(@assembly1)
```

##### `collection.destroy(object, ...)`

2048
The `collection.destroy` method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
2049 2050 2051 2052 2053

```ruby
@part.assemblies.destroy(@assembly1)
```

2054
##### `collection=(objects)`
2055

2056
The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate. The changes are persisted to the database.
2057 2058 2059 2060 2061 2062 2063 2064 2065

##### `collection_singular_ids`

The `collection_singular_ids` method returns an array of the ids of the objects in the collection.

```ruby
@assembly_ids = @part.assembly_ids
```

2066
##### `collection_singular_ids=(ids)`
2067

2068
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. The changes are persisted to the database.
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093

##### `collection.clear`

The `collection.clear` method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.

##### `collection.empty?`

The `collection.empty?` 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 %>
```

##### `collection.size`

The `collection.size` method returns the number of objects in the collection.

```ruby
@assembly_count = @part.assemblies.size
```

##### `collection.find(...)`

2094 2095
The `collection.find` method finds objects within the collection. It uses the same syntax and options as
[`ActiveRecord::Base.find`](http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find).
2096 2097 2098 2099 2100 2101 2102

```ruby
@assembly = @part.assemblies.find(1)
```

##### `collection.where(...)`

2103
The `collection.where` 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.
2104 2105 2106 2107 2108 2109 2110

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

##### `collection.exists?(...)`

2111 2112 2113
The `collection.exists?` method checks whether an object meeting the supplied
conditions exists in the collection. It uses the same syntax and options as
[`ActiveRecord::Base.exists?`](http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F).
2114 2115 2116 2117 2118 2119

##### `collection.build(attributes = {})`

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.

```ruby
2120
@assembly = @part.assemblies.build({assembly_name: "Transmission housing"})
2121 2122 2123 2124 2125 2126 2127
```

##### `collection.create(attributes = {})`

The `collection.create` 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, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.

```ruby
2128
@assembly = @part.assemblies.create({assembly_name: "Transmission housing"})
2129 2130
```

2131 2132
##### `collection.create!(attributes = {})`

2133
Does the same as `collection.create`, but raises `ActiveRecord::RecordInvalid` if the record is invalid.
2134

2135 2136 2137 2138 2139 2140 2141 2142
##### `collection.reload`

The `collection.reload` method returns a Relation of all of the associated objects, forcing a database read. If there are no associated objects, it returns an empty Relation.

```ruby
@assemblies = @part.assemblies.reload
```

2143 2144
#### Options for `has_and_belongs_to_many`

2145
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_and_belongs_to_many` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
2146 2147

```ruby
2148
class Parts < ApplicationRecord
2149 2150
  has_and_belongs_to_many :assemblies, -> { readonly },
                                       autosave: true
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
end
```

The `has_and_belongs_to_many` association supports these options:

* `:association_foreign_key`
* `:autosave`
* `:class_name`
* `:foreign_key`
* `:join_table`
* `:validate`

##### `:association_foreign_key`

By convention, Rails assumes 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
2170
class User < ApplicationRecord
S
Sunny Ripert 已提交
2171
  has_and_belongs_to_many :friends,
2172 2173 2174
      class_name: "User",
      foreign_key: "this_user_id",
      association_foreign_key: "other_user_id"
2175 2176 2177 2178 2179
end
```

##### `:autosave`

2180
If you set the `:autosave` option to `true`, Rails will save any loaded association members and destroy members that are marked for destruction whenever you save the parent object. Setting `:autosave` to `false` is not the same as not setting the `:autosave` option. If the `:autosave` option is not present, then new associated objects will be saved, but updated associated objects will not be saved.
2181 2182 2183 2184 2185 2186

##### `:class_name`

If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is `Gadget`, you'd set things up this way:

```ruby
2187
class Parts < ApplicationRecord
2188
  has_and_belongs_to_many :assemblies, class_name: "Gadget"
2189 2190 2191 2192 2193 2194 2195 2196
end
```

##### `:foreign_key`

By convention, Rails assumes 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
2197
class User < ApplicationRecord
2198 2199 2200 2201
  has_and_belongs_to_many :friends,
      class_name: "User",
      foreign_key: "this_user_id",
      association_foreign_key: "other_user_id"
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
end
```

##### `:join_table`

If the default name of the join table, based on lexical ordering, is not what you want, you can use the `:join_table` option to override the default.

##### `:validate`

If you set the `:validate` option to `false`, then associated objects will not be validated whenever you save this object. By default, this is `true`: associated objects will be validated when this object is saved.

#### Scopes for `has_and_belongs_to_many`

There may be times when you wish to customize the query used by `has_and_belongs_to_many`. Such customizations can be achieved via a scope block. For example:

```ruby
2218
class Parts < ApplicationRecord
2219
  has_and_belongs_to_many :assemblies, -> { where active: true }
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
end
```

You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:

* `where`
* `extending`
* `group`
* `includes`
* `limit`
* `offset`
* `order`
* `readonly`
* `select`
2234
* `distinct`
2235 2236 2237 2238 2239 2240

##### `where`

The `where` method lets you specify the conditions that the associated object must meet.

```ruby
2241
class Parts < ApplicationRecord
2242 2243 2244 2245 2246 2247 2248 2249
  has_and_belongs_to_many :assemblies,
    -> { where "factory = 'Seattle'" }
end
```

You can also set conditions via a hash:

```ruby
2250
class Parts < ApplicationRecord
2251
  has_and_belongs_to_many :assemblies,
2252
    -> { where factory: 'Seattle' }
2253 2254 2255 2256 2257 2258 2259
end
```

If you use a hash-style `where`, 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".

##### `extending`

N
Nishant Modak 已提交
2260
The `extending` method specifies a named module to extend the association proxy. Association extensions are discussed in detail [later in this guide](#association-extensions).
2261 2262 2263 2264 2265 2266

##### `group`

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

```ruby
2267
class Parts < ApplicationRecord
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
  has_and_belongs_to_many :assemblies, -> { group "factory" }
end
```

##### `includes`

You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used.

##### `limit`

The `limit` method lets you restrict the total number of objects that will be fetched through an association.

```ruby
2281
class Parts < ApplicationRecord
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
  has_and_belongs_to_many :assemblies,
    -> { order("created_at DESC").limit(50) }
end
```

##### `offset`

The `offset` method 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.

##### `order`

The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).

```ruby
2296
class Parts < ApplicationRecord
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
  has_and_belongs_to_many :assemblies,
    -> { order "assembly_name ASC" }
end
```

##### `readonly`

If you use the `readonly` method, then the associated objects will be read-only when retrieved via the association.

##### `select`

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

2310
##### `distinct`
2311

2312
Use the `distinct` method to remove duplicates from the collection.
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337

#### When are Objects Saved?

When you assign an object to a `has_and_belongs_to_many` association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.

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 `collection.build` method.

### Association Callbacks

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.

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:

* `before_add`
* `after_add`
* `before_remove`
* `after_remove`

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

```ruby
2338 2339
class Author < ApplicationRecord
  has_many :books, before_add: :check_credit_limit
2340

2341
  def check_credit_limit(book)
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
    ...
  end
end
```

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
2352 2353
class Author < ApplicationRecord
  has_many :books,
2354
    before_add: [:check_credit_limit, :calculate_shipping_charges]
2355

2356
  def check_credit_limit(book)
2357 2358 2359
    ...
  end

2360
  def calculate_shipping_charges(book)
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
    ...
  end
end
```

If a `before_add` callback throws an exception, the object does not get added to the collection. Similarly, if a `before_remove` callback throws an exception, the object does not get removed from the collection.

### Association Extensions

You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:

```ruby
2373 2374 2375 2376
class Author < ApplicationRecord
  has_many :books do
    def find_by_book_prefix(book_number)
      find_by(category_id: book_number[0..2])
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390
    end
  end
end
```

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
    where("created_at > ?", 5.days.ago)
  end
end

2391 2392
class Author < ApplicationRecord
  has_many :books, -> { extending FindRecentExtension }
2393 2394
end

2395
class Supplier < ApplicationRecord
2396 2397 2398 2399 2400 2401 2402 2403
  has_many :deliveries, -> { extending FindRecentExtension }
end
```

Extensions can refer to the internals of the association proxy using these three attributes of the `proxy_association` accessor:

* `proxy_association.owner` returns the object that the association is a part of.
* `proxy_association.reflection` returns the reflection object that describes the association.
2404
* `proxy_association.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`.
2405 2406 2407 2408 2409

Single Table Inheritance
------------------------

Sometimes, you may want to share fields and behavior between different models.
A
Anthony Crumley 已提交
2410
Let's say we have Car, Motorcycle, and Bicycle models. We will want to share
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
the `color` and `price` fields and some methods for all of them, but having some
specific behavior for each, and separated controllers too.

Rails makes this quite easy. First, let's generate the base Vehicle model:

```bash
$ rails generate model vehicle type:string color:string price:decimal{10.2}
```

Did you note we are adding a "type" field? Since all models will be saved in a
single database table, Rails will save in this column the name of the model that
is being saved. In our example, this can be "Car", "Motorcycle" or "Bicycle."
STI won't work without a "type" field in the table.

Next, we will generate the three models that inherit from Vehicle. For this,
we can use the `--parent=PARENT` option, which will generate a model that
inherits from the specified parent and without equivalent migration (since the
table already exists).

For example, to generate the Car model:

```bash
$ rails generate model car --parent=Vehicle
```

The generated model will look like this:

```ruby
class Car < Vehicle
end
```

This means that all behavior added to Vehicle is available for Car too, as
associations, public methods, etc.

Creating a car will save it in the `vehicles` table with "Car" as the `type` field:

```ruby
A
Andrey Nering 已提交
2449
Car.create(color: 'Red', price: 10000)
2450 2451 2452 2453 2454
```

will generate the following SQL:

```sql
A
Andrey Nering 已提交
2455
INSERT INTO "vehicles" ("type", "color", "price") VALUES ('Car', 'Red', 10000)
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
```

Querying car records will just search for vehicles that are cars:

```ruby
Car.all
```

will run a query like:

```sql
SELECT "vehicles".* FROM "vehicles" WHERE "vehicles"."type" IN ('Car')
```