0
0
Ruby on Railsframework~5 mins

has_one relationship in Ruby on Rails

Choose your learning style9 modes available
Introduction

The has_one relationship links two models so one model owns exactly one related model. It helps organize data clearly.

When a user has exactly one profile.
When a car has exactly one engine.
When a company has exactly one headquarters address.
When an order has exactly one payment detail.
Syntax
Ruby on Rails
class User < ApplicationRecord
  has_one :profile
end

Use has_one in the model that owns the other model.

The related model usually has a foreign key pointing back.

Examples
User has one Profile, and Profile belongs to User. This sets up a one-to-one link.
Ruby on Rails
class User < ApplicationRecord
  has_one :profile
end

class Profile < ApplicationRecord
  belongs_to :user
end
Each Car has one Engine. Engine stores the car_id foreign key.
Ruby on Rails
class Car < ApplicationRecord
  has_one :engine
end

class Engine < ApplicationRecord
  belongs_to :car
end
Sample Program

This example shows an Author with one Biography. We create both and then print the biography content through the author.

Ruby on Rails
class Author < ApplicationRecord
  has_one :biography
end

class Biography < ApplicationRecord
  belongs_to :author
end

# Usage in Rails console
author = Author.create(name: "Jane Doe")
biography = Biography.create(content: "Writer and traveler.", author: author)

puts author.biography.content
OutputSuccess
Important Notes

Always add belongs_to on the related model for proper linking.

Use database foreign keys to keep data consistent.

Access the related object easily via the has_one association.

Summary

has_one sets a one-to-one connection from one model to another.

The related model uses belongs_to to link back.

This helps keep data organized and easy to access.