Set Up Belongs To

This guide shows you how to set up a belongs_to relationship where one model references another via a foreign key.

When to Use

Use belongs_to when:

  • A Comment belongs to a Post

  • An Order belongs to a User

  • A Photo belongs to an Album

The model with belongs_to holds the foreign key.

Schema Setup

Create tables with a foreign key column:

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

schema.table :comments do
  primary :id, Int64, auto_increment: true
  column :body, String
  column :post_id, Int64, null: false
  timestamps

  foreign_key [:post_id], references: :posts, references_columns: [:id]
end
schema.comments.create!

Define the Relationship

Add belongs_to to the child model:

Access the Parent

Create with Parent

Set Foreign Key Directly

Set via Association

Build Associated Parent

Build a parent without saving:

Create Associated Parent

Create and save parent in one step:

Optional Belongs To

For optional relationships, make the foreign key nullable:

Verify It Works

Last updated

Was this helpful?