Rails. Polymorphic Associations.

Julia
3 min readOct 13, 2020

If you ever learned Ruby on Rails you should be familiar with Active Record associations, most common are:
belongs_to, has_many, has_many :through.

Recently I’ve started working on a new project. My MVP (minimum viable product) looked pretty simple, only 3 models : Company, Technician and Review. Review should belongs to either a Company model or a Technician Model. Here I run into a problem and started thinking, how do I implement the relationship where a model can belong to one OR another model, on a single association. It should be something that I don't know. I started googling. There is always something new to learn about Ruby on Rails :)
The answer was found, Polymorphic Associations.
Here is a short but useful tutorial how to set up Polymorphic Associations.

Declare your models associations taking as an example next samples from my project.

Models

You can retrieve technician reviews as @technician.reviews. Here is how my Show Method looks like. (same about Company reviews)

Technicians Controller

For getting the parent of Review(who the review belongs to) use @Review.object

Reviews Controller

What about DB tables? How does the Schema supposed to look? As you can guess the Review table should have foreign key, in my project it’s object_id, which is going to represent Company id or Technician id. Here we can face another problem: for rails it’s still not clear how to get a right object, the Company instance and Technician instance might have the same id. That is why it is necessary to have one more column in Review Table: object_type, which is going to hold the name of the class who the Review belongs to.

Migration file

The desired result, reviews might belong to either a Company instance or a Technician instance.

--

--