Polymorphic Associations




Rails Coach show

Summary: Rails has the concept of Polymorphic associations, which are associations that can be of different data types. For example, let’s say we have a Comment model. A comment in your app can be on a post or a page. Rather than creating a PostComment model and a PageComment model, you can set up your Comment model to have a polymorphic association to a Page or a Post. Generally people call these associations “something-able”. In this case, it would be commentable. Here’s a quick code sample: class Comment true end class Page :commentable end class Post :commentable end The only other thing you need to know is the database structure. On the database, you need two columns. A [polymorphic-association-name]_type string column and [polymorphic-association-name]_id integer column. In this case, it would be “commentable_type” and “commentable_id”.