Skip to content

Commit

Permalink
Merge pull request #21076 from r11runner/guide-join-tables
Browse files Browse the repository at this point in the history
migration and association guides: added some remarks about join tables
  • Loading branch information
claudiob committed Aug 4, 2015
2 parents 17eb642 + d73a524 commit 98ce161
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
18 changes: 8 additions & 10 deletions guides/source/active_record_migrations.md
Expand Up @@ -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
Expand All @@ -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:
Expand Down
13 changes: 13 additions & 0 deletions guides/source/association_basics.md
Expand Up @@ -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:
Expand Down

0 comments on commit 98ce161

Please sign in to comment.