Set Up Many-to-Many

This guide shows you how to set up a many-to-many relationship using a join table.

When to Use

Use many-to-many when:

  • A Post has many Tags, and a Tag has many Posts

  • A User belongs to many Groups, and a Group has many Users

  • A Product is in many Categories, and a Category has many Products

Schema Setup

Create three tables: two main tables and a join table.

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

Last updated

Was this helpful?