mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Different Ways To Add A Foreign Key Reference as a Rails til
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||
|
||||
_1096 TILs and counting..._
|
||||
_1097 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -669,6 +669,7 @@ _1096 TILs and counting..._
|
||||
- [Customize The Path Of A Resource Route](rails/customize-the-path-of-a-resource-route.md)
|
||||
- [Delete Paranoid Records](rails/delete-paranoid-records.md)
|
||||
- [Demodulize A Class Name](rails/demodulize-a-class-name.md)
|
||||
- [Different Ways To Add A Foreign Key Reference](rails/different-ways-to-add-a-foreign-key-reference.md)
|
||||
- [Disambiguate Where In A Joined Relation](rails/disambiguate-where-in-a-joined-relation.md)
|
||||
- [Ensure Migrations Use The Latest Schema](rails/ensure-migrations-use-the-latest-schema.md)
|
||||
- [Force All Users To Sign Out](rails/force-all-users-to-sign-out.md)
|
||||
|
||||
47
rails/different-ways-to-add-a-foreign-key-reference.md
Normal file
47
rails/different-ways-to-add-a-foreign-key-reference.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# Different Ways To Add A Foreign Key Reference
|
||||
|
||||
A foreign key reference creates a relationship between two tables that is
|
||||
guaranteed by a foreign key constraint.
|
||||
|
||||
This is a minimal example.
|
||||
|
||||
```ruby
|
||||
create_table :books
|
||||
t.references :author, foreign_key: true
|
||||
end
|
||||
```
|
||||
|
||||
The `foreign_key: true` is needed here, otherwise just the reference column is
|
||||
created without a backing constraint. When `foreign_key` is true, an index will
|
||||
be created for the column as well.
|
||||
|
||||
This is a maximal example.
|
||||
|
||||
```ruby
|
||||
create_table :books
|
||||
t.references :author, index: true, foreign_key: true, type: :uuid, null: false
|
||||
end
|
||||
```
|
||||
|
||||
It is explicit about the foreign key and index. It specifies a `not null`
|
||||
constraint. It declares the type as `uuid` assuming the `authors` table's
|
||||
primary key is of type `uuid`.
|
||||
|
||||
Here is an example with a custom column name.
|
||||
|
||||
```ruby
|
||||
create_table :books
|
||||
t.references :written_by, foreign_key: { to_table: :authors }
|
||||
end
|
||||
```
|
||||
|
||||
Here is adding a reference to an existing table.
|
||||
|
||||
```ruby
|
||||
def up
|
||||
add_reference :books, :author, index: true, foreign_key: true
|
||||
end
|
||||
```
|
||||
|
||||
There are more combinations of these, but I hope there is enough here to be
|
||||
able to iterate to a solution that works for you.
|
||||
Reference in New Issue
Block a user