2
votes

Ok so here is my situation. Im a PHP developer recently turned Rails developer. In PHP code the use of abstract classes as "base" classes is a pretty common pattern. When moving onto my current Rails application I did a lot of the "pre-planning" with PHP ideas in my head which are now giving me a bit of a headache.

I have many different types of Invoices. In PHP I would create an abstract class and have my different types of Invoices that extend that class. I would DRY things up by keeping duplicate code in the abstract class and life is good. In rails things work a bit differently.

I can't seem to find a pattern that fits perfectly to my preconceptions. STI is nice but I HATE the idea of all the Null fields since each invoice will have many different fields. I have come close with Polymorphic associations using a module to DRY up my code. However, everywhere I look polymorphic associations are used differently then the way I intend. For example, in the railscast there are three different classes that each need to use comments. Its not exactly the same thing.

So here is my question: I already know how to use a module to DRY up my code, but how can I use polymorphic associations to provide similar modularity to my code as the "base" classes do in php? FYI I can't use STI because there is no limit on how many different types of invoices could end up coming into existence. For now its 1, but in a month it could be 20.

1

1 Answers

3
votes

There is another option you can use: Multiple Table Inheritance. It is a bit more complex to set up, but it'll give you some of the advantages that are not present in STI and some that are not present with polymorphic associations. Check this post to see how to make this work.