Railsのmigrationでテーブル定義やカラム追加を行うときはコメントを入れるようにしよう

こんにちは!kossyです!




さて、今回はRailsのmigrationでテーブル定義やカラム追加を行うときにコメントを入れる方法を
ブログに残してみたいと思います。




環境
Ruby 2.6.3
Rails 6.0.3
MacOS Catalina



commentオプションを使えば簡単に定義できる

Rails5系からcommentオプションを使うことで簡単にschemaにコメントを定義できるようになりました。

以下のように定義します。

# テーブル定義の場合

t.text :action, null: false, comment: 'Behavior such as login is stored in json format.'
t.string :performer, null: false, comment: 'Store polymorphic related class names.'
t.string :performer_type, null: false, comment: 'Store polymorphic related class names.'
t.string :ip_address, comment: 'store remote_ip address in Ipv4 format.'

# カラム追加の場合

add_column :activity_logs, :action, :text, null: false, comment: 'Behavior such as login is stored in json format.'
add_column :activity_logs, :performer, :string, null: false, comment: 'Store polymorphic related class names.'
add_column :activity_logs, :performer_type, :string, null: false, comment: 'Store polymorphic related class names.'
add_column :activity_logs, :ip_address, :string, comment: 'store remote_ip address in Ipv4 format.'


私はチームが多国籍で構成されていることを想定して英語で記載していますが。もちろん日本語でも問題ありません。
チームのコーディングルールに従うべきでしょう。

このようにcommentオプションを用いてマイグレーションを実行すると、

db/schema.rb

  create_table "activity_logs", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t|
    t.bigint "tenant_id", null: false
    t.text "action", null: false, comment: "Behavior such as login is stored in json format."
    t.string "performer", null: false, comment: "Store polymorphic related class names."
    t.string "performer_type", null: false, comment: "Store polymorphic related class names."
    t.string "ip_address", comment: "store remote_ip address in Ipv4 format."
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["ip_address"], name: "index_activity_logs_on_ip_address"
    t.index ["performer"], name: "index_activity_logs_on_performer"
    t.index ["performer_type"], name: "index_activity_logs_on_performer_type"
    t.index ["tenant_id"], name: "index_activity_logs_on_tenant_id"
  end

schema.rbにcomment定義されます。

1人で個人開発してるくらいのレベルならいらない機能かもしれませんが、
複数人で中〜大規模(テーブル数50 ~ )のアプリケーション開発をするなら、
是非行っておきたい定義ですね。



勉強になりました。



参考にさせていただいたサイト