annotate
を使うと、rake db:migrate
をしたタイミングで、自動でmodelクラスの先頭に、スキーマ情報のコメントを挿入してくれるようになります。
設定
まずはインストール。Gemfileに追加後 bundle install
します。
cat Gemfile
gem 'annotate'
$ bundle install
`rake db:migrate`をしたタイミングで自動で、スキーマ情報を挿入するためには、 `annotate:install` します。
$ rails g annotate:install
create lib/tasks/auto_annotate_models.rake
自動で挿入したくない場合は、annotate:install
はせずに、modelクラスを更新した都度、bundle exec annotate
を行って下さい。
$ bundle exec annotate
確認
試しにbooksモデルを作成し、コメントが挿入されるか確認してみます。
$ rails g scaffold Book title:string price:integer
$ rake db:migrate
== 20150330032832 CreateBooks: migrating ======================================
– create_table(:books)
-> 0.0090s
== 20150330032832 CreateBooks: migrated (0.0094s) =============================
Annotated (1): Book
modelクラスにスキーマ情報が挿入されていることを確認できます。
$ cat app/models/book.rb
== Schema Information
#
Table name: books
#
id :integer not null, primary key
title :string
price :integer
created_at :datetime not null
updated_at :datetime not null
#
class Book < ActiveRecord::Base
end
カラムを追加、変更後も自動でスキーマ情報が更新されます。
$ rails g migration AddAuthorsToBooks author:string
$ cat db/migrate/20150330024524_add_authors_to_books.rb
class AddAuthorsToBooks < ActiveRecord::Migration
def change
add_column :books, :author, :string
end
end
$ rake db:migrate
$ cat app/models/book.rb
== Schema Information
#
Table name: books
#
id :integer not null, primary key
title :string
price :integer
created_at :datetime not null
updated_at :datetime not null
author :string # <= This!
#
class Book < ActiveRecord::Base
end