Railsアプリを開発している時、テーブルのカラム情報を確認したい時があります。
db/migrate以下のファイルを追うのは結構面倒くさいし、rails dbconsoleなんかでみるのもなんとなく面倒くさいです。
そこで役立つのがannotatorというgem。早速試してみましょう。
インストール
インストールはいつもどおり、Gemfileに
gem 'annotator'
と書けばOK。bundle installしておきます。
さて、まずはコメントを挿入するモデルを作ります。
rails g model LineItem quantity:integer product_id:integer unit_price:float order_id:integer
作成されるmigrationファイルは次のようになります。
class CreateLineItems < ActiveRecord::Migration def change create_table :line_items do |t| t.integer :quantity t.integer :product_id t.float :unit_price t.integer :order_id t.timestamps end end end
テーブルを作成します。
rake db:migrate
その後、annotateコマンドを実行します。
tsubame.local{miyohide}% annotate Annotated (1): LineItem tsubame.local{miyohide}%
すると、app/models/line_item.rbには次のようなコメントが入っています。
# == 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
ちなみに、db:migrateを実行し忘れると、次のようなエラーメッセージが出てしまいます。
Unable to annotate line_item.rb: Could not find table 'line_items' (/Users/miyohide/.rvm/gems/ruby-1.9.2-p290@blogtest/gems/activerecord-3.2.2/lib/active_record/connection_adapters/sqlite_adapter.rb:465:in `table_structure')
Nothing annotated.
削除するなら-dオプションで。
tsubame.local{miyohide}% annotate -d Removed annotation from: LineItem tsubame.local{miyohide}%
綺麗に削除されています。
class LineItem < ActiveRecord::Base end
今回はここまで。次回は、カラムの追加と削除について試してみます。