Set Up Has Many

This guide shows you how to set up a has_many relationship where one model has multiple related records.

When to Use

Use has_many when:

  • A User has many Posts

  • A Post has many Comments

  • A Category has many Products

Schema Setup

schema.table :users do
  primary :id, Int64, auto_increment: true
  column :name, String
  timestamps
end
schema.users.create!

schema.table :posts do
  primary :id, Int64, auto_increment: true
  column :user_id, Int64, null: false
  column :title, String
  column :body, String
  timestamps

  foreign_key [:user_id], references: :users, references_columns: [:id]
  index [:user_id]
end
schema.posts.create!

Define the Relationship

Add has_many to the parent model:

Delete Specific Posts

Delete All Posts

Cascade Delete with Foreign Keys

Configure foreign key to cascade deletes:

Now when a user is deleted, their posts are automatically deleted.

Verify It Works

Last updated

Was this helpful?