polymorphic associations in ruby on rails
Polymorphic associations allow a model to belong to more than one other model within a single association. This is helpful in building my capstone, as I want to be able to associate images with users or playing cards. To set this up, I go into my Image model must contain two syntax-specific variables: imageable_type and imageable_id.
imageable_id is the id of the association and imageable_type is the variable which allows me to explicitly associate the image with either a user or a card. Then, in order to set up my associations, I type the following in my Image model:
After the polymorphic associations are defined in my Card model and my User model are defined like so:
This is basically saying is imageable_type = user, then that image is associated with user. On the other hand, is imageable_type = card, then it becomes the image for a card. As intimidating as “polymorphic associations” sound, they’re actually fairly easy to set-up and lend my app a much-needed degree of flexibility.