0
0
RailsHow-ToBeginner · 3 min read

How to Use has_one in Rails: Simple Guide with Examples

In Rails, use has_one in a model to declare a one-to-one association with another model. It means each instance of the declaring model owns exactly one instance of the associated model, which you can access with simple method calls.
📐

Syntax

The has_one association is declared inside a Rails model to specify a one-to-one connection with another model. It tells Rails that this model owns one instance of the other model.

  • has_one :associated_model - declares the association.
  • The associated model usually has a belongs_to pointing back.
  • You can add options like dependent: :destroy to control behavior on deletion.
ruby
class User < ApplicationRecord
  has_one :profile, dependent: :destroy
end

class Profile < ApplicationRecord
  belongs_to :user
end
💻

Example

This example shows a User model that has_one :profile. You can create a user and then create or access their profile easily.

ruby
class User < ApplicationRecord
  has_one :profile, dependent: :destroy
end

class Profile < ApplicationRecord
  belongs_to :user
end

# Usage in Rails console or controller
user = User.create(name: "Alice")
user.create_profile(bio: "Loves coding")
puts user.profile.bio  # Outputs: Loves coding
Output
Loves coding
⚠️

Common Pitfalls

Common mistakes when using has_one include:

  • Not adding belongs_to in the associated model, which breaks the link.
  • Forgetting to add foreign keys in the database (e.g., user_id in profiles table).
  • Misunderstanding that has_one expects the foreign key on the associated model, not the declaring model.
  • Not handling dependent records, which can leave orphaned data.

Example of a wrong and right way:

ruby
# Wrong: Missing belongs_to
class User < ApplicationRecord
  has_one :profile
end

class Profile < ApplicationRecord
  # belongs_to :user missing
end

# Right:
class Profile < ApplicationRecord
  belongs_to :user
end
📊

Quick Reference

OptionDescription
has_one :association_nameDeclares a one-to-one association.
dependent: :destroyDeletes the associated record when owner is deleted.
class_name: 'ModelName'Specifies a custom associated model name.
foreign_key: 'key_name'Specifies a custom foreign key on the associated model.
inverse_of: :associationImproves bi-directional association behavior.

Key Takeaways

Use has_one in the owner model to declare a one-to-one association.
The associated model must have belongs_to pointing back with a foreign key.
Add dependent: :destroy to clean up associated records automatically.
Ensure the database has the foreign key on the associated model's table.
Access the associated object with simple method calls like user.profile.