Rails 3.1 Model Inheritance without Table Inheritance

Most inheritance questions I've seen assume that the child classes have different attributes than the super class. For example, Person may be the super class, and Driver a subclass, where Driver has everything Person has plus a license_type field.

I'm asking a slightly different question. I have a super class, call it Entity, and Entity has an object_type field, describing what type of Entity we have. All types have the same fields, but each type behaves slightly differently. For example, the add method is different for different Entity types.

My currently solution is to subclass Entity and whenever I fetch an Entity (e.g., in find() or where(..)), I call entity = entity.becomes(eval("Entity#{entity.object_type}")). This is ugly and doesn't work that well, for example url_for and form_for will call undefined methods, because the class type is Entity<Type>, not Entity.

How would I go about having model inheritance without table inheritance, such that urls, paths, forms, and everything else still works as described? And maybe there's a way for me to avoid calling .becomes(..), too? What I'm doing is very ugly ;).


I've learned more about Ruby and Rails and I've come up with a good solution. I changed my Entity<Type> classes to modules and put them in lib/. Then, in the Entity class, I have an after_initialize callback that looks like this:

if object_type == "Type1"
  extend EntityType1
elsif object_type == "Type2"
  extend EntityType2

This way, all the methods defined in EntityType1 and EntityType2 are executed in the scope of the Entity class, without requiring any new class instantiation. So far the solution has been working well, though I've only been using it for a few days now.

Need Your Help

Automated integration testing a C++ app with a database

c++ database automated-tests integration-testing

I am introducing automated integration testing to a mature application that until now has only been manually tested.

Pulling elements from a large string with PHP using CSS style selectors?

php css facebook soap css-selectors

I have the following long string returned from a SOAP call into a variable, and I need to find the contents of certain elements within it, namely the .MoreInfoZone .OfferZone #Heading .content and