DEV Community

Cover image for Ruby On Rails: Multiple roles for a given model
Jack Kim
Jack Kim

Posted on • Updated on

Ruby On Rails: Multiple roles for a given model

While working on my final project for my software engineer course at Flatiron School, I have learned about many different interesting model associations. There was one particular model association that drew me in the most, which is a model that consists of multiple roles.

Click here for more details on the multiple roles for the given model.

It took me several days to grasp how one model can have multiple roles. My understanding of a model is that the instances from a model should be identifiable as one unique instance but with the concept of "multiple roles", a model can create instances that can behave like two different instances.

To give an example of multiple roles, here is three of the four models for my project.

User model

Event model

Event Attendee model

Please take a closer look at my User model. It has a coordinator_id and attendee_id. It does not appear to look right because there are more than one ID attributes (technically 3 IDs including user_id). However, notice that the differently named ID attributes are used as a foreign key or belongs_to for associating User model to the other two models. This tells me that the instances of coordinator and attendees of the User model can be associated to the other two models.

Concisely speaking, the implemented "multiple roles" to my model association allows the Event model to have both an instance of coordinator and multiple instances of event attendee from the User model with the proper model association using foreign key and belongs_to. This means that an event can have both the coordinator and attendees at the same time. Therefore, it was not necessary to create additional models for Coordinator and Attendee model.

Image description

Image description

In conclusion, my understanding of the "multiple roles" is that it associates one model to the other through the joined table (EventAttendee joins User and Event models like a bridge) by using foreign key and class_name so that the models know where to look for the corresponding ID of the instances from the class_name models.

I strongly recommend reading about the multiple roles in which it provides more details on the multiple roles for the given model. It is critical to understand the basic model associations such as belongs_to, has_many to clearly understand the "multiple roles".


Multiple roles:

Cover image:

Top comments (0)