0
0
Ruby on Railsframework~5 mins

belongs_to relationship in Ruby on Rails

Choose your learning style9 modes available
Introduction

The belongs_to relationship connects one model to another, showing that one item belongs to a single parent item.

When a comment belongs to a single post in a blog.
When an order belongs to a specific customer in a store.
When a book belongs to one author in a library system.
When a profile belongs to a user account.
Syntax
Ruby on Rails
class ChildModel < ApplicationRecord
  belongs_to :parent_model
end

The child model uses belongs_to to link to the parent model.

This sets up methods to access the parent from the child.

Examples
This means each comment is linked to one post.
Ruby on Rails
class Comment < ApplicationRecord
  belongs_to :post
end
Each order belongs to a single customer.
Ruby on Rails
class Order < ApplicationRecord
  belongs_to :customer
end
A profile is connected to one user account.
Ruby on Rails
class Profile < ApplicationRecord
  belongs_to :user
end
Sample Program

This example shows a post with many comments. Each comment belongs to one post. When we print comment.post.title, it shows the title of the post the comment belongs to.

Ruby on Rails
class Post < ApplicationRecord
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :post
end

# Usage example in Rails console
post = Post.create(title: "Hello World")
comment = Comment.create(body: "Nice post!", post: post)
puts comment.post.title
OutputSuccess
Important Notes

Always add a foreign key column (e.g., post_id) in the child table for belongs_to to work.

Rails 5+ requires belongs_to associations to be present by default, meaning the child must have a parent.

Summary

belongs_to links a child model to one parent model.

It creates easy access from child to parent.

Use it when one item clearly belongs to another single item.