Skip to content

Commit

Permalink
Add a section on creating tables with composite primary keys
Browse files Browse the repository at this point in the history
  • Loading branch information
noahgibbs committed Sep 8, 2023
1 parent 099f979 commit 5ee23cb
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions guides/source/active_record_migrations.md
Expand Up @@ -623,6 +623,33 @@ NOTE: Active Record only supports single column foreign keys. `execute` and
`structure.sql` are required to use composite foreign keys. See
[Schema Dumping and You](#schema-dumping-and-you).

### Composite Primary Keys

Sometimes a single column's value isn't enough to uniquely identify every row
of a table, but a combination of two or more columns *does* uniquely identify
it. This can be the case when using a legacy database schema without a single
`id` column as a primary key, or when altering schemas for sharding or
multitenancy.

You can create a table with a composite primary key by passing the
`:primary_key` option to `create_table` with an array value:

```ruby
class CreateProducts < ActiveRecord::Migration[7.1]
def change
create_table :products, primary_key: [:customer_id, :product_sku] do |t|
t.integer :customer_id
t.string :product_sku
t.text :description
end
end
end
```

INFO: Tables with composite primary keys require passing array values rather
than integer IDs to many methods. See also the [Active Record Querying](
active_record_querying.html) guide to learn more.

### When Helpers aren't Enough

If the helpers provided by Active Record aren't enough you can use the [`execute`][]
Expand Down

0 comments on commit 5ee23cb

Please sign in to comment.