Set Up Many-to-Many
When to Use
Schema Setup
schema.table :posts do
primary :id, Int64, auto_increment: true
column :title, String
timestamps
end
schema.posts.create!
schema.table :tags do
primary :id, Int64, auto_increment: true
column :name, String
timestamps
end
schema.tags.create!
# Join table
schema.table :post_tags do
column :post_id, Int64, null: false
column :tag_id, Int64, null: false
column :created_at, Time
foreign_key [:post_id], references: :posts, references_columns: [:id], on_delete: :cascade
foreign_key [:tag_id], references: :tags, references_columns: [:id], on_delete: :cascade
index [:post_id]
index [:tag_id]
index [:post_id, :tag_id], unique: true
end
schema.post_tags.create!Define the Models
Post Model
Tag Model
Join Table Model
Create Relationships
Add Tags to a Post
Create Join Records Directly
Query Through Join Table
Get Tags for a Post
Get Posts for a Tag
Find Posts with Specific Tag
Remove Relationships
Remove a Tag from Post
Remove All Tags from Post
Verify It Works
Related
Last updated
Was this helpful?