Wednesday, February 6, 2013

Rails Polymorphic Association

Updated on March 26, 2014
Updated on Sep 21, 2014

Let's create a scenario where polymorphic association can be used. Assume an online store (like Amazon) keeps the data of different type of items in several different tables, such as books, laptops and cell_phones.These tables have different attributes. There is another table called orders to keep track of all the items that's been ordered by customers.

This orders table has a one-to-one relationship to all the other three tables, which means it must have three different foreign keys pointing to these three tables. This is a bad design because for each order record there are two columns that are not used. You might say why not create three different tables called order_books, order_laptops and order_cell_phones. But you will find these are three identical table serving the same functionality. So here is where polymorphic association comes in.

To use polymorphic association, you need to add another attribute called "type" (rails will automatically do it for you when you define a polymorphic association) to determine which table an order record is associated to, and thus only a single foreign key is needed instead of three. Below is how polymorphic association is defined using our example.



Instead of using a specific table, model Order use a universal name "item" to refer to the other three tables. If you look into the database, you will find an attribute called "type" in table orders. Using the "type" and the foreign key, the orders table is able to uniquely point to an item, whether it's a book, a laptop or a cell phone.

No comments:

Post a Comment