Programming Journal

学習したことの整理用です。

'type' カラムの追加でエラー

typeカラムを追加したらエラーが

実務で既存のテーブルに新たに「種別」を示すカラムを追加したく、typeというカラムを追加しました。
※参考コードは実務のではなく適当なサンプルです。

class AddTypeToPayment < ActiveRecord::Migration[5.1]
  def change
    add_column :payment, :type, :integer, null: false, default: 0
  end
end

rails db:migrateも正常に終わったものの、カラムを追加したテーブルを参照しているページでエラーが。

ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: '0'. 
This error is raised because the column 'type' is reserved for storing the class in case of inheritance. 

Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite ActiveRecordModel::Payment.
inheritance_column to use another column for that information.

from /usr/local/bundle/gems/activerecord-5.1.4/lib/active_record/inheritance.rb:196:in `rescue in find_sti_class'

'type'カラムは予約語だから、名前を変えてね。とのこと。

Railsガイドにも記載がありました。知らなかった。

railsguides.jp

これらのカラム名は必須ではありませんが、Active Recordで予約されています。特別な理由のない限り、これらの予約済みカラム名の利用は避けてください。たとえば、typeという語はテーブルでSTI(Single Table Inheritance)を指定するために予約されています。STIを使わない場合であっても、予約語より先にまず「context」などのようなモデルのデータを適切に表す語を検討してください。