2008/08/28

Rails で migration 時に、Column Comment を設定する

Railsで、マイグレーション作成時に、カラムにコメントを設定し、それをデータベースに設定する ColumnComments という便利なプラグインがあります。

というか、標準では設定できないんですね・・・。


インストールは次の通りです。



  1. こちらより、ZIPファイルをダウンロード

  2. 解凍して column_comments ディレクトリを vendor/plugins へコピー


使い方は、マイグレーション時に次のように記述します。


Example migration:

def self.up
create_table "users" do |t|
t.column "first_name", :string, :comment => "The member's given name."
end

column_comment "tags", "id", "The unique ID of any tag in the system."
end

そしてさらに、テーブルの情報を model と fixture にコメントとして書き込んでくれる annotate_models プラグインもバンドルされています。が、 annotate_models.rb が古いので、こちらは本家のものと置き換えて、コメントを表示するように修正します。


ついでに、 annotate_modelsにindexの情報を付加する - Hello, world! - s21g を参考に、インデックス情報もつけちゃいます。


vendor/plugins/column_comments/lib/annotate_models.rb - self.get_schema_info
  def self.get_schema_info(klass, header)
info = "# #{header}\n#\n"
info << "# Table name: #{klass.table_name}\n#\n"

# index info by http://blog.s21g.com/articles/318
indices = {}
klass.connection.indexes(klass.table_name).each do |index|
index.columns.each do |column_name|
indices[column_name] ||= []
indices[column_name] << "#{index.name}"
indices[column_name].last << "(unique)" if index.unique
end
end

max_size = klass.column_names.collect{|name| name.size}.max + 1
klass.columns.each do |col|
attrs = []
attrs << "default(#{quote(col.default)})" if col.default
attrs << "not null" unless col.null
attrs << "primary key" if col.name == klass.primary_key
if index = indices[col.name]
attrs << index.join(' ')
end

col_type = col.type.to_s
if col_type == "decimal"
col_type << "(#{col.precision}, #{col.scale})"
else
col_type << "(#{col.limit})" if col.limit
end
info << sprintf("# %-#{max_size}.#{max_size}s:%-15.15s %s", col.name, col_type, attrs.join(", ")).rstrip
info << "\n"
# column comment
unless col.comment.blank?
info << "# #{col.comment}"
info << "\n"
end
end

info << "#\n\n"
end

使い方は、次の Rake タスクを実行します。


rake annotate_models

これでもう、テーブルのカラム名を調べるためにデータベースを見る必要はなくなりそうです。

0 件のコメント: