Set Up Has One

This guide shows you how to set up a has_one relationship where one model has exactly one related model.

When to Use

Use has_one when:

  • A User has one Profile

  • An Order has one ShippingAddress

  • A Company has one Address

The other model holds the foreign key.

Schema Setup

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

schema.table :profiles do
  primary :id, Int64, auto_increment: true
  column :user_id, Int64, null: false
  column :bio, String
  column :avatar_url, String

  foreign_key [:user_id], references: :users, references_columns: [:id]
  index [:user_id], unique: true
  timestamps
end
schema.profiles.create!

Note: The unique index ensures only one profile per user.

Define the Relationship

Add has_one to the parent model:

Create Profile for User

Build and Save

Verify It Works

Last updated

Was this helpful?