Rails STI and the development environment

I’m using single table inheiritance (STI) to model the foods people eat and use in recipes in SF. STI is a way of representing a class and its subclasses in a single database table.

The system defines a WeightPortion is a UserPortion is a Portion and there are a couple of other subclasses too.

Rails handles this pretty well in the case that it has loaded all the subclasses into memory and worked out these relationships. In the development environment for Rails, though, it reloads class definitions for every request so you don’t have to start/stop your server everytime you make a code change. That means that Rails doesn’t always load all of the subclass definitions and that’s when you hit trouble, asking for all UserPortions wont get you all WeightPortions, the subclass, back… your finder just searches on type = ‘UserPortion’ instead of type = ‘UserPortion’ and type = ‘WeightPortion’.

You have to force Rails to read all of the subtypes by putting a require into your controller… icky:

require_dependency 'weight_portion'

I added all these to application_controller.rb so that they’re centrally managed and available everywhere.

Link to a rather dramatic/hysterical write up on the frustration this causes.

Link to another method for solving this that did nothing but crash my app but that might still be worth some investigation.

One Response to “Rails STI and the development environment”

  1. Tim’s Internet Web Log » Blog Archive » Rails Single Table Inheiritance and class loading Says:

    [...] I might have mentioned this before but you should be very aware of how your development environment loads and caches STI classes. Update: yeah, I did mention this before. [...]

Leave a Reply