Single Table Inheritence and Fixtures

Setting up a fixture for an STI table is fairly simple. The inheritence column (the default is ‘type’, but can be overridden) should be set as appropriate for each yml entry. If you are making use of foreign keys via a ‘belongs_to’, set for :foreign_key as the general foreign key from the base class. This way, you can make use of the ‘foreign_table: yml_object’ shortcut instead of excplicitly setting foreign ids. For example, consider the following table, and subclasses representing fruit and the kind of on which it grows:

create_table :fruits do |t|
  t.integer "number"
  t.integer "plant_id"
  t.string  "kind"
end

class Fruit < ActiveRecord::Base
  self.inheritance_column = 'kind'
end

class Apple < Fruit
  belongs_to :tree, :foreign_key => 'plant_id'
end

class Watermelon < Fruit
  belongs_to :vine, :foreign_key => 'plant_id'
end

Assume we also have a Plant and Tree model, with a apple_tree and watermelon_vine defined respectively.
The fruits.yml fixture can be setup as follows:

watermelon:
  number: 10
  vine: watermelon_vine
  kind: "Vine"
apple:
  number: 50
  tree: apple_tree
  kind: "Tree"

Using ‘plant’ will confuse the test runner, but ‘plant_id’ can still be used to explicitly give the id of an object.