From 930e180d9ffb21efbd519e26070ef01a8c546094 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 30 May 2019 19:59:33 -0500 Subject: [PATCH] Add Add A Foreign Key Reference To A Table as a rails til --- README.md | 3 +- .../add-a-foreign-key-reference-to-a-table.md | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 rails/add-a-foreign-key-reference-to-a-table.md diff --git a/README.md b/README.md index ada02b8..d690c2f 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_816 TILs and counting..._ +_817 TILs and counting..._ --- @@ -474,6 +474,7 @@ _816 TILs and counting..._ ### Rails +- [Add A Foreign Key Reference To A Table](rails/add-a-foreign-key-reference-to-a-table.md) - [Add React With Webpacker To A New Rails App](rails/add-react-with-webpacker-to-a-new-rails-app.md) - [Access Secrets In A Rails 5.2 App](rails/access-secrets-in-a-rails-5-2-app.md) - [ActiveRecord Query For This Or That](rails/active-record-query-for-this-or-that.md) diff --git a/rails/add-a-foreign-key-reference-to-a-table.md b/rails/add-a-foreign-key-reference-to-a-table.md new file mode 100644 index 0000000..dfe79f7 --- /dev/null +++ b/rails/add-a-foreign-key-reference-to-a-table.md @@ -0,0 +1,33 @@ +# Add A Foreign Key Reference To A Table + +Foreign keys are a great way to maintain referential integrity within our data. +We can add reference columns with foreign key constraints using the Rails +migration DSL. + +Here is how we include one as part of creating a table: + +```ruby +def up + create_table :books do |t| + # ... other columns + + t.references :author, index: true, foreign_key: true + end +end +``` + +This will add a column, `author_id`, to the `books` table that references the +`authors` table. It will have both a foreign key constraint and an index +applied to it. + +Here is how we do the same for an existing table: + +```ruby +def up + add_reference :books, :author, index: true, foreign_key: true +end +``` + +As of Rails 5, this is a bit verbose as `index: true` happens by default. +Though I'm always in favor of explicitness. If for whatever reason you don't +want an index, you will have to specify `index: false`.