diff --git a/README.md b/README.md index da75715..48d9123 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/rails/different-ways-to-add-a-foreign-key-reference.md b/rails/different-ways-to-add-a-foreign-key-reference.md new file mode 100644 index 0000000..f9d163b --- /dev/null +++ b/rails/different-ways-to-add-a-foreign-key-reference.md @@ -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.