Skip to content

Commit 3658b4d

Browse files
committed
Add Different Ways To Add A Foreign Key Reference as a Rails til
1 parent b27b44d commit 3658b4d

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1096 TILs and counting..._
13+
_1097 TILs and counting..._
1414

1515
---
1616

@@ -669,6 +669,7 @@ _1096 TILs and counting..._
669669
- [Customize The Path Of A Resource Route](rails/customize-the-path-of-a-resource-route.md)
670670
- [Delete Paranoid Records](rails/delete-paranoid-records.md)
671671
- [Demodulize A Class Name](rails/demodulize-a-class-name.md)
672+
- [Different Ways To Add A Foreign Key Reference](rails/different-ways-to-add-a-foreign-key-reference.md)
672673
- [Disambiguate Where In A Joined Relation](rails/disambiguate-where-in-a-joined-relation.md)
673674
- [Ensure Migrations Use The Latest Schema](rails/ensure-migrations-use-the-latest-schema.md)
674675
- [Force All Users To Sign Out](rails/force-all-users-to-sign-out.md)
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Different Ways To Add A Foreign Key Reference
2+
3+
A foreign key reference creates a relationship between two tables that is
4+
guaranteed by a foreign key constraint.
5+
6+
This is a minimal example.
7+
8+
```ruby
9+
create_table :books
10+
t.references :author, foreign_key: true
11+
end
12+
```
13+
14+
The `foreign_key: true` is needed here, otherwise just the reference column is
15+
created without a backing constraint. When `foreign_key` is true, an index will
16+
be created for the column as well.
17+
18+
This is a maximal example.
19+
20+
```ruby
21+
create_table :books
22+
t.references :author, index: true, foreign_key: true, type: :uuid, null: false
23+
end
24+
```
25+
26+
It is explicit about the foreign key and index. It specifies a `not null`
27+
constraint. It declares the type as `uuid` assuming the `authors` table's
28+
primary key is of type `uuid`.
29+
30+
Here is an example with a custom column name.
31+
32+
```ruby
33+
create_table :books
34+
t.references :written_by, foreign_key: { to_table: :authors }
35+
end
36+
```
37+
38+
Here is adding a reference to an existing table.
39+
40+
```ruby
41+
def up
42+
add_reference :books, :author, index: true, foreign_key: true
43+
end
44+
```
45+
46+
There are more combinations of these, but I hope there is enough here to be
47+
able to iterate to a solution that works for you.

0 commit comments

Comments
 (0)