How to Use belongs_to in Rails: Simple Guide with Examples
In Rails, use
belongs_to inside a model to set up a one-to-one connection with another model, indicating that each instance belongs to one instance of the other model. This creates methods to access the associated object and requires a foreign key in the database table.Syntax
The belongs_to method is placed inside a model class to declare an association where each record belongs to one record of another model. It expects the name of the associated model as a symbol.
- Model with belongs_to: The model that holds the foreign key.
- Associated model: The model that the current model belongs to.
- Foreign key: A column in the database table that stores the ID of the associated model.
ruby
class Comment < ApplicationRecord
belongs_to :post
endExample
This example shows two models: Post and Comment. Each comment belongs to one post. The comments table has a post_id column as a foreign key.
Using belongs_to :post in the Comment model lets you call comment.post to get the post it belongs to.
ruby
class Post < ApplicationRecord has_many :comments end class Comment < ApplicationRecord belongs_to :post end # Usage in Rails console post = Post.create(title: "Hello World") comment = Comment.create(body: "Nice post!", post: post) puts comment.post.title
Output
Hello World
Common Pitfalls
Common mistakes when using belongs_to include:
- Not adding the foreign key column (e.g.,
post_id) in the database table. - Forgetting to run migrations after adding
belongs_to. - Using
belongs_towithout the matchinghas_manyorhas_onein the associated model (not mandatory but recommended for clarity). - Assuming
belongs_tocreates the foreign key automatically (it does not).
Wrong:
class Comment < ApplicationRecord belongs_to :post end # But no post_id column in comments table
Right:
class AddPostIdToComments < ActiveRecord::Migration[7.0]
def change
add_reference :comments, :post, null: false, foreign_key: true
end
endQuick Reference
| Term | Description |
|---|---|
| belongs_to :model_name | Declares the model belongs to another model |
| Foreign key | Column in this model's table linking to associated model's ID |
| has_many :model_names | Declares the other model has many of this model |
| add_reference migration | Adds foreign key column with index and constraints |
Key Takeaways
Use belongs_to in the model that holds the foreign key to link to another model.
Always add the foreign key column in the database with a migration.
belongs_to creates methods to access the associated object easily.
Pair belongs_to with has_many or has_one in the related model for clarity.
Check migrations and schema to avoid missing foreign keys causing errors.