Search code examples
ruby-on-railsrubymigrationsingle-table-inheritance

How do I add a column to my derived classes with STI?


I already have single table inheritance set up, with the type column in my form_field model and my number_field and text_field classes inheriting from the form_field.

Consider the following (when I fire up rails console):

2.1.1 :001 > nf = NumberField.new
 => #<NumberField id: nil, label: nil, created_at: nil, updated_at: nil, type: "NumberField"> 
2.1.1 :002 > nf.is_a? FormField
 => true 

I tried the following migration(s):

class AddInputToNumberFields < ActiveRecord::Migration
  def change
    add_column :number_fields, :input, :integer
  end
end

However, when I run rake db:migrate, the console complains saying I can't add the column because :number_fields is not a table (STI so the table is :form_fields).

I've looked around for quite a while, but no SO question or Google link explains it explicitly.


Solution

  • You need to add columns to the base class of your STI table. If NumberField inherits from FormField, then add the columns to form_fields. You've basically answered your own question by observing this.

    Remember STI stands for "Single Table Inheritance" so there is only one table that can be modified.