Search code examples
ruby-on-railsactiverecordpolymorphismmodelssti

Relating my models/tables? STI? Polymorphic?


I currently have three models: Business, Charity, and Organization. A business and charity are both types of organizations because they share many similar attributes (e.g. address, hours, website, etc.) however they each have their own unique attributes. How should I best handle the creation of the models in Active Record? Use STI or Polymorphism? Or should I break out each one into their own model with duplicate information and get rid of the Organization model?


Solution

  • You can use both, so it is not necessarily an either/or situation. Most importantly, however, is how you will structure your tables and the logic surrounding them, which depends on how you are going to query the data, and how these elements relate to one another.

    There is not enough information above to give you very clear direction on what to use. However, if after reading:

    1. Rails Guides
    2. How and When to Use STI

    ... the solution isn't clear, here are some simple rules:

    1. if the types of objects you are using mostly have the same attributes but have different business logic attached to them (ie, the behavior written into their Model classes), then STI is a good baseline idea, but
    2. if they have the same logic as well, it may make sense just to create them as a single class with a "type" flag (but not the attribute type, since it is only for STI)

    As far as polymorphism goes, it seems like these Models are all very similar and interchangeable -- polymorphism is more useful for relating unlike things (such as comments and photos) to another Model (such as a FB post). In that case, using either a single table or STI and relating based on the parent table may make more sense.