1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Create A Join Table With The Migration DSL as a rails til

This commit is contained in:
jbranchaud
2021-03-23 19:19:43 -05:00
parent 3340d6fa52
commit 26777dd8ac
2 changed files with 41 additions and 1 deletions

View File

@@ -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)

View File

@@ -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.