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 ofPicturesandVideos.I would like to provide an ActiveRecord helper on my
Articlethat reads likeArticle.first.mediathat 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 ofPicturesandVideosthat are polymorphically related to a givenArticleI suppose this could be done by asking for
Article.first.picturesand joining that manually withArticle.first.videosThis post explains why it is at least tricky if not impossible to traverse a polymorphic
:throughrelationship in the "other" direction