Techie December 2022
Definition
In Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models and therefore eliminating the need to add multiple index columns for the respective associations.
Application Example
There are three models: review.rb, movie.rb, actor.rb
A review belongs to both a movie and an actor. There are two ways to create these associations:
1. By Adding movie_id and actor_id columns in reviews table
With this approach, you create the movie_id and actor_id columns in reviews table and then edit the associations in the models like so:
There’s no problem with this, it works just fine. But wait, what if you start having additional other tables that have a similar association with reviews? That will quickly become redundant and that’s where polymorphic associations come to our rescue.
2. Using a polymorphic association
The first approach works well but as we have seen, it can become unnecessarily messy. A polymorphic association can help us avoid that. Essentially, since both the movies and the actors table have a similar association with the reviews table, then we can definitely use shared generic columns to map these associations.
When using the polymorphic approach, rails creates a virtual table to represent the the table that has associations with multiple other tables. In this case, the reviews table.
i). Configure a virtual table for reviews and call it something like reviewable.
ii). Map the virtual table to the other tables like so:
iii). Add the generic columns for the virtual table on the table in focus (reviews table)
The name of the class is stored in the reviewable_type column so that rails can
use that in combination with the reviewable_id to determine the records associated with them.
iv). Test it
Rails can automatically query the database using the polymorphic association:
Thanks for reading, see you in the next one!