It's pretty easy to do polymorphic associations in Rails: A Picture can belong to either a BlogPost or an Article. But what if you need the relationship the other way around? A Picture, a Text and a Video can belong to an Article, and that article can find all media by calling @article.media
This example shows how to create an ArticleElement join model that handles the polymorphic relationship. To add fields that are common to all polymorphic models, add fields to the join model.
I have the same question as @kbighorse
The issue I have with the answer given by @ayrton is that the result would be an array of
ArticleElements
, not an array ofPictures
andVideos
.I would like to provide an ActiveRecord helper on my
Article
that reads likeArticle.first.media
that does not bring back a bunch of joins, but reaches through the join and assembles a list of what is on the other side of that polymorphic table, i.e. a mix ofPictures
andVideos
that are polymorphically related to a givenArticle
I suppose this could be done by asking for
Article.first.pictures
and joining that manually withArticle.first.videos
This post explains why it is at least tricky if not impossible to traverse a polymorphic
:through
relationship in the "other" direction