Last Updated: February 25, 2016
·
2.047K
· strangnet

Legacy database, Single table inheritance and Ruby on Rails

Single Table Inheritance in Ruby on Rails means that you store the class name of the subclass in the type column in the database table. However, if that value stored by the legacy system doesn't follow the Ruby way, you just have to make sure that the class affected overrides the class method find_sti_class(type_name).

The following example would store and expect the value WineGlass and BeerGlass in the type column by default. To be able to reuse existing semantics you make sure each class defines its sti_name, and the superclass handles the logic for mapping the type value to an actual class.

id | type       | price
1  | wine_glass | 100
2  | beer_glass | 75
class Glass < ActiveRecord::Base
  def self.find_sti_class(type_name)
    type_name.camelize.constantize
  end
end

class BeerGlass < Glass
  def self.sti_name
    :beer_glass
  end
end

class WineGlass < Glass
  def self.sti_name
    :wine_glass
  end
end