From 26777dd8accb85a0bf7827b3d0d240eed9aada55 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 23 Mar 2021 19:19:43 -0500 Subject: [PATCH] Add Create A Join Table With The Migration DSL as a rails til --- README.md | 3 +- ...ate-a-join-table-with-the-migration-dsl.md | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 rails/create-a-join-table-with-the-migration-dsl.md diff --git a/README.md b/README.md index 242826b..84f75eb 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). -_1093 TILs and counting..._ +_1094 TILs and counting..._ --- @@ -661,6 +661,7 @@ _1093 TILs and counting..._ - [Convert A Symbol To A Constant](rails/convert-a-symbol-to-a-constant.md) - [Count The Number Of Records By Attribute](rails/count-the-number-of-records-by-attribute.md) - [Create A Custom Named References Column](rails/create-a-custom-named-references-column.md) +- [Create A Join Table With The Migration DSL](rails/create-a-join-table-with-the-migration-dsl.md) - [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md) - [Custom Validation Message](rails/custom-validation-message.md) - [Customize Paths And Helpers For Devise Routes](rails/customize-paths-and-helpers-for-devise-routes.md) diff --git a/rails/create-a-join-table-with-the-migration-dsl.md b/rails/create-a-join-table-with-the-migration-dsl.md new file mode 100644 index 0000000..a67a695 --- /dev/null +++ b/rails/create-a-join-table-with-the-migration-dsl.md @@ -0,0 +1,39 @@ +# Create A Join Table With The Migration DSL + +The Rails migration DSL comes with a helper for creating a join table between +two other existing tables. + +Call `create_join_table` with two arguments, symbols for the names of the two +tables. + +```ruby +def change + create_join_table :tags, :posts +end +``` + +This will create a table with id references columns to each of the tables. The +`db/schema.rb` addition will look something like this: + +```ruby + create_table "posts_tags", id: false, force: :cascade do |t| + t.bigint "tag_id", null: false + t.bigint "post_id", null: false + end +``` + +A Rails/ActiveRecord convention that comes into play for the creation of this +table. + +1. The name should be the pluralized versions of the two joined table names. +2. The joined table names should show up in the table name in alphabetical + order. + +Notice that despite listing `:tags` before `:posts` it creates a table called +`posts_tags`. The DSL handles that for us. + +Some `create_join_table` defaults to be aware of: + +- It doesn't generate foreign key constraints. +- It uses `bigint` (or `int`) for the keys (even if those tables use UUIDs). +- The references are named after their respective table names.