Rails Single Table/Collection Inheritance

dieutb
Towards Dev
Published in
2 min readApr 10, 2022

--

Single Table Inheritance

This strategy is quite common when we have many subclasses that are similar to each other, but we want to store all the data in a table/collection (polymorphism).

ActiveRecord — Single Table Inheritance

  • In order to turn it on, we need to config the inheritance_column
  • We should not use this strategy if the number of different fields is too large, it would cause waste storage in the table.

MongoDB — Single Collection Inheritance

  • Because MongoDB is a NoSQL database, the field only existed when it has a valid value. So, there is no wasting storage if there is a numerous of different fields.
  • By default, inheritance in MongoId supports the strategy of Single Collection Inheritance. An inherited class / sub_class just needs to extend the parent / super_class.
  • MongoId would auto-generate the field _type to specify subclass.

MongoId — Separated Collection Inheritance

  • In contrast to Single Collection Inheritance, in this case, we need to store separated collections for each subclass.
  • In scenario A, we want to inherit from an existing model and we do not want to create a module concern. Because MongoId does not allow the inherited one changes the storage_options, we need to override its inherited method.
  • In scenario B, we do create a concern that contains all fields and methods in common.

References

--

--

passion in finding solutions and research some things relate to technical and helpful in life. Also strongly interest in foods, travel, and gentle music :)