Search code examples
inheritanceember-dataassociationsrails-postgresqlrails-api

Correct associations and database design without (single table) inheritance for Rails-Ember


I'm struggling to figure out how to design my PostgreSQL database tables and Rails API models such that their associations can be implemented 1:1 in my Ember front-end, whereby Ember and Rails can communicate fluidly through commonly understood JSON. (I'm using ActiveModelSerializers on the Rails side, and ActiveModelAdapter on the Ember side.)

The basic idea before I started writing any code: rough class diagram

  • Product can be Type1, Type2 etc., that is, the sub types inherit product (I thought of it as an abstract class - nothing's supposed to be just a product)
  • each Type1 can have several Type2 as part of it, and each Type2 can belong to several Type1, via the Type2_container
  • each Type class has many unique attributes, but also many general attributes via the Product class
  • Source refers to one Product and one Shop, i.e. Products have many Shops through Sources

Now the challenge is: I can't just implement Inheritance like this in Rails which only supports Single Table Inheritance. With STI, the Product table would be 50+ columns wide, of which only 10 or so would be shared between the inheriting classes. Not ideal...

On the other hand, I don't know how I can make a simple 1:1 relationship between Product and Type1/2/3 so that

  1. each Product always points to exactly one of the Type tables, and
  2. both Rails and Ember Data know how to interpret that association between Product and Type1/2/3, so that each time I retrieve/modify a Product in Ember, I also retrieve/modify its Type-specific attributes.

A third option I considered - an Attribute table with columns "name", "value_num", "value_int", "value_boolean" and "value_text". Product would has_many Attribute, each Attribute would belongs_to Product. This would do away with the Type-tables, but would also result in an unnecessarily large number of rows (e.g. 100 products with 40 attributes each = 4000 rows, vs. just 200 with a Product-Type association). And it would make it more difficult to access a products attributes (?).

Any help is appreciated. Also, if you'd rather suggest a different database/frontend/backend entirely for what I want to achieve, please do. I'm new to most of this, don't know about all the pros and cons of different approaches, and I'm not in a massive hurry with this.


Solution

  • Decided to make Product polymorphic, fits my scenario perfectly. No need to worry about having any database table for Product, it just works. This is the guide I followed: emberigniter.com