モデルにテーブルのカラム情報をコメントで追加してくれるannotator(カラムの追加と削除編)

前回の続きです。

カラムの追加

開発を続けていくとカラムの追加、削除は当たり前のように発生します。今回はカラムの追加と削除をやってみましょう。

rails g migration add_field1_to_line_item field1:string

migrationファイルは次のようになります。

class AddField1ToLineItem < ActiveRecord::Migration
  def change
    add_column :line_items, :field1, :string

  end
end

忘れないようにdb:migrateします。

rake db:migrate

で、annotateコマンドを実行します。

tsubame.local{miyohide}% annotate
Annotated (1): LineItem
tsubame.local{miyohide}%

結果を確認しましょう。

# == Schema Information
#
# Table name: line_items
#
#  created_at :datetime         not null
#  field1     :string(255)
#  id         :integer          not null, primary key
#  order_id   :integer
#  product_id :integer
#  quantity   :integer
#  unit_price :float
#  updated_at :datetime         not null
#

class LineItem < ActiveRecord::Base
end

おぉ!ちゃんと追加されていますね。

カラムの削除

では、追加したカラムを削除します。

rails g migration RemoveField1FromLineItem

と書いても

class RemoveField1FromLineItem < ActiveRecord::Migration
  def up
  end

  def down
  end
end

のように空のメソッドしか作られないので、自分で書いておきます。

class RemoveField1FromLineItem < ActiveRecord::Migration
  def up
     remove_column :line_items, :field1
  end

  def down
     add_column :line_items, :field1
  end
end

で、migration

tsubame.local{miyohide}% rake db:migrate
==  RemoveField1FromLineItem: migrating =======================================
-- remove_column(:line_items, :field1)
   -> 0.0497s
==  RemoveField1FromLineItem: migrated (0.0498s) ==============================

tsubame.local{miyohide}% 

annotateでコメントを作成し、作成されたコメントを確認します。

tsubame.local{miyohide}% annotate
Annotated (1): LineItem
tsubame.local{miyohide}%

>|ruby| 
# == Schema Information
#
# Table name: line_items
#
#  created_at :datetime         not null
#  id         :integer          not null, primary key
#  order_id   :integer
#  product_id :integer
#  quantity   :integer
#  unit_price :float
#  updated_at :datetime         not null
#

class LineItem < ActiveRecord::Base
end
tsubame.local{miyohide}%   

おぉ!ちゃんと削除されていますね。

README.rdocをみるとより高度なことができそうなのですが、とりあえずここまでで。