未验证 提交 ce646199 编写于 作者: R Rafael França 提交者: GitHub

Merge pull request #31800 from rlue/doc/association-basics-guide

Fix example migrations in Associations guide
......@@ -572,40 +572,32 @@ class Book < ApplicationRecord
end
```
This declaration needs to be backed up by the proper foreign key declaration on the books table:
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:
```ruby
class CreateBooks < ActiveRecord::Migration[5.0]
def change
create_table :books do |t|
t.datetime :published_at
t.string :book_number
t.integer :author_id
t.datetime :published_at
t.string :book_number
t.references :author
end
end
end
```
If you create an association some time after you build the underlying model, you need to remember to create an `add_column` migration to provide the necessary foreign key.
It's a good practice to add an index on the foreign key to improve queries
performance and a foreign key constraint to ensure referential data integrity:
Whereas for an existing table, it might look like this:
```ruby
class CreateBooks < ActiveRecord::Migration[5.0]
class AddAuthorToBooks < ActiveRecord::Migration[5.0]
def change
create_table :books do |t|
t.datetime :published_at
t.string :book_number
t.integer :author_id
end
add_index :books, :author_id
add_foreign_key :books, :authors
add_reference :books, :author
end
end
```
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.
#### Creating Join Tables for `has_and_belongs_to_many` Associations
If you create a `has_and_belongs_to_many` association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the `:join_table` option, Active Record creates the name by using the lexical 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.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册