提交 d73a524b 编写于 作者: R r11runner

[ci skip] migration and association guides: added some remarks about join tables

上级 10e994cc
......@@ -357,8 +357,8 @@ will append `ENGINE=BLACKHOLE` to the SQL statement used to create the table
### Creating a Join Table
Migration method `create_join_table` creates an HABTM join table. A typical use
would be:
The migration method `create_join_table` creates an HABTM (has and belongs to
many) join table. A typical use would be:
```ruby
create_join_table :products, :categories
......@@ -367,23 +367,21 @@ create_join_table :products, :categories
which creates a `categories_products` table with two columns called
`category_id` and `product_id`. These columns have the option `:null` set to
`false` by default. This can be overridden by specifying the `:column_options`
option.
option:
```ruby
create_join_table :products, :categories, column_options: {null: true}
create_join_table :products, :categories, column_options: { null: true }
```
will create the `product_id` and `category_id` with the `:null` option as
`true`.
You can pass the option `:table_name` when you want to customize the table
name. For example:
By default, the name of the join table comes from the union of the first two
arguments provided to create_join_table, in alphabetical order.
To customize the name of the table, provide a `:table_name` option:
```ruby
create_join_table :products, :categories, table_name: :categorization
```
will create a `categorization` table.
creates a `categorization` table.
`create_join_table` also accepts a block, which you can use to add indices
(which are not created by default) or additional columns:
......
......@@ -622,6 +622,19 @@ end
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.
You can also use the method `create_join_table`
```ruby
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration
def change
create_join_table :assemblies, :parts do |t|
t.index :assembly_id
t.index :part_id
end
end
end
```
### 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:
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册