Home / Companies / Semaphore / Blog / Post Details
Content Deep Dive

Rails Techniques: Using Polymorphic Associations

Blog post from Semaphore

Post Details
Company
Date Published
Author
Jovan Ivanovic
Word Count
1,014
Language
English
Hacker News Points
-
Summary

In Ruby on Rails, polymorphic associations enable a model to be connected to multiple other models through a single association, as demonstrated with a Review model linked to both Event and Restaurant models. This setup uses a generic entity called Reviewable, facilitated by two database columns, reviewable_id and reviewable_type, which store the ID and type of the associated entity. The article details the implementation process, including creating a migration to alter the database schema and setting up the association in the Review model. It also involves creating a shared spec example and a concern called Reviewable to abstract the has_many side, which is included in the Event and Restaurant models. The article concludes by demonstrating the functionality with instantiated objects, showcasing the utility of polymorphic associations, and highlighting Semaphore's tools for improving continuous integration in Rails projects.