0
0
Ruby on Railsframework~30 mins

Polymorphic associations in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Polymorphic Associations in Rails
📖 Scenario: You are building a simple Rails app where users can comment on different types of content: articles and photos. Instead of creating separate comment tables for each content type, you will use polymorphic associations to let comments belong to either articles or photos.
🎯 Goal: Create a Rails setup where Comment can belong to either an Article or a Photo using polymorphic associations.
📋 What You'll Learn
Create Article and Photo models with a title attribute
Create a Comment model that belongs to a polymorphic commentable
Set up the associations in all models correctly
Demonstrate creating comments for both articles and photos
💡 Why This Matters
🌍 Real World
Polymorphic associations let you reuse one model (like Comment) for many different related models (like Article and Photo) without duplicating tables or code.
💼 Career
Understanding polymorphic associations is important for Rails developers to design flexible and maintainable database relationships in real applications.
Progress0 / 4 steps
1
Create Article and Photo models
Create two Rails models called Article and Photo. Each model should have a string attribute called title. Use Rails generators or write the model classes with title attribute.
Ruby on Rails
Need a hint?

Use rails generate model Article title:string and rails generate model Photo title:string or define classes with title attribute.

2
Add Comment model with polymorphic association
Create a Rails model called Comment with a string attribute body. Add polymorphic references commentable to this model. This means Comment belongs to commentable polymorphically.
Ruby on Rails
Need a hint?

Use rails generate model Comment body:string commentable:references{polymorphic} or define the class with belongs_to :commentable, polymorphic: true.

3
Set up associations in Article and Photo models
In the Article and Photo models, add the association to comments using has_many :comments, as: :commentable. This sets up the polymorphic connection from the other side.
Ruby on Rails
Need a hint?

Add has_many :comments, as: :commentable inside both Article and Photo classes.

4
Create comments for articles and photos
Write code to create an Article with title 'Rails Guide' and a Photo with title 'Sunset'. Then create a Comment with body 'Great article!' for the article, and a Comment with body 'Beautiful photo!' for the photo. Use the polymorphic association to link comments.
Ruby on Rails
Need a hint?

Create instances of Article and Photo with the given titles. Then create Comment instances linking to these using commentable: option.