Skip to content

Commit e5a50ad

Browse files
committed
Add Create A Custom Named References Column as a Rails til
1 parent a3cf90c commit e5a50ad

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-
_1068 TILs and counting..._
13+
_1069 TILs and counting..._
1414

1515
---
1616

@@ -649,6 +649,7 @@ _1068 TILs and counting..._
649649
- [Comparing DateTimes Down To Second Precision](rails/comparing-datetimes-down-to-second-precision.md)
650650
- [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md)
651651
- [Convert A Symbol To A Constant](rails/convert-a-symbol-to-a-constant.md)
652+
- [Create A Custom Named References Column](rails/create-a-custom-named-references-column.md)
652653
- [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md)
653654
- [Custom Validation Message](rails/custom-validation-message.md)
654655
- [Customize Paths And Helpers For Devise Routes](rails/customize-paths-and-helpers-for-devise-routes.md)
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Create A Custom Named References Column
2+
3+
The `t.references` and `add_reference` methods both create a foreign key column
4+
name based on the target table.
5+
6+
For instance,
7+
8+
```ruby
9+
add_reference :guests, :user, foreign_key: true, index: true, null: false
10+
```
11+
12+
would create a `user_id` column on the `guests` table.
13+
14+
At times, you'll need to customize the name of the foreign key column. The
15+
Rails migration DSL supports this with the `foreign_key` option.
16+
17+
Here is an example that shows the syntax for both a new table and an existing
18+
table.
19+
20+
```ruby
21+
class AddInvitedByColumnToUser < ActiveRecord::Migration[6.1]
22+
def change
23+
create_table :guests, id: :uuid do |t|
24+
t.string :email, null: false
25+
t.timestamps
26+
27+
t.references :invited_by,
28+
type: :uuid,
29+
index: true,
30+
null: false,
31+
foreign_key: { to_table: :users }
32+
end
33+
34+
add_reference :guests, :signed_up_as,
35+
type: :uuid,
36+
index: true,
37+
null: false,
38+
foreign_key: { to_table: :users }
39+
end
40+
end
41+
```
42+
43+
The `t.references` call creates a foreign key column to the `users` table named
44+
`invited_by`. The `add_reference` call adds a `signed_up_as` foreign key column
45+
to `guests` that points to users.
46+
47+
[source](https://stackoverflow.com/a/42056089/535590)

0 commit comments

Comments
 (0)