2

I have to model an association structure and the association is divided into divisions/subdivisions/sections etc. So I've created a simple Entity-Attribute Model:

alt text

I'd like to use rail's single-table-inheritance but it seems like this works only if the type column is a string. My question is how to achieve this with my approach? Since I'm using a foreign key as "type" I'd have to query the "type name" first. Has anybody done this before?

sled
  • 14,525
  • 3
  • 42
  • 70

1 Answers1

1

I would recommend adding a String "type" attribute to your structure table to satisfy single table inheritance, and to add before_save callbacks to set correct values on either table.

Say you have a StructureType with name "Basic". In Rails that means you'd want to have class hierarchy:

Structure < ActiveRecord::Base BasicStructure < Structure

In Structure class add:

before_create :set_structure_type_fk

def set_structure_type_fk
  self.structure_type = StructureType.find_by_name(\ 
      self.class.name.gsub(/Structure/, '').downcase)
end

Hope this helps.

Note that this approach means that StructureType.name should be immutable: once created it should never be changed, except by a database migration that updates both tables correspondingly.

K