Skip to content

Commit 0fffba8

Browse files
committed
Add Add A Reference Column With An Index as a rails til
1 parent 51b2856 commit 0fffba8

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

README.md

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

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

12-
_901 TILs and counting..._
12+
_902 TILs and counting..._
1313

1414
---
1515

@@ -515,6 +515,7 @@ _901 TILs and counting..._
515515

516516
- [Add A Check Constraint To A Table](rails/add-a-check-constraint-to-a-table.md)
517517
- [Add A Foreign Key Reference To A Table](rails/add-a-foreign-key-reference-to-a-table.md)
518+
- [Add A Reference Column With An Index](rails/add-a-reference-column-with-an-index.md)
518519
- [Add React With Webpacker To A New Rails App](rails/add-react-with-webpacker-to-a-new-rails-app.md)
519520
- [Access Secrets In A Rails 5.2 App](rails/access-secrets-in-a-rails-5-2-app.md)
520521
- [ActiveRecord Query For This Or That](rails/active-record-query-for-this-or-that.md)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Add A Reference Column With An Index
2+
3+
Though I prefer to always back my reference columns with a [foreign
4+
key](add-a-foreign-key-reference-to-a-table.md), sometimes you may just want to
5+
add the reference column on its own. Though this could be done manually with
6+
the `add_column` directive, you can be more explicit with `add_reference` --
7+
which allows you to specify whether or not an index is to be added.
8+
9+
```ruby
10+
def up
11+
add_reference :books, :authors, index: true
12+
end
13+
```
14+
15+
This will add `authors_id` and an index to the `books` table.
16+
17+
You can additionally specify the type of the column. This is handy if you are
18+
using `uuid`s for all your primary keys.
19+
20+
```ruby
21+
def up
22+
add_reference :books, :authors, type: :uuid, index: true
23+
end
24+
```
25+
26+
[source](https://nandovieira.com/using-uuid-with-postgresql-and-activerecord)

0 commit comments

Comments
 (0)