カスタム タイプの列を使用して、既存のテーブルに STI を追加したいと考えています。対応するモデルがフルーツであるこの味のタイプを呼び出しましょう。
Fruit モデルには次のものがあります。
set_inheritance_column :taste_type
STI を追加するための移行では、次のものがあります。
class AddSTI < ActiveRecord::Migration
def self.up
add_column :fruits, :taste_type, :string, :limit => 100, :null => false
Fruit.reset_column_information
Fruit.find_by_id(1).update_attributes({:taste_type => 'Sour'})
end
def self.down
remove_column :fruits, :taste_type
end
end
移行を実行すると、次のエラーが表示されます。
Mysql::Error: Column 'taste_type' cannot be null: ...
何が起こっているのか分かりますか?Fruit モデルの set_inheritance_column にコメントを付け、移行の実行後にコメントを解除すると、移行を実行できます。明らかに、私はこれをしたくありませんが。