Tbpgr Blog

Recruiting Operations tbpgr(てぃーびー) のブログ

Ruby on Rails | テーブルのカラム名変更

概要

テーブルのカラム名変更

詳細

テーブルのカラム名変更をします。

実施

hogeテーブルのhoge列をhige列にリネームします。

rails g migration rename_hoge_hoge
class RenameHogeHoge < ActiveRecord::Migration
  def up
    rename_column :hoges, :hoge, :hige
  end

  def down
    rename_column :hoges, :hige, :hoge
  end
end
rake db:migrate

変更前

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| hoge       | varchar(255) | YES  |     | NULL    |                |
| created_at | datetime     | YES  |     | NULL    |                |
| updated_at | datetime     | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

変更後

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| hige       | varchar(255) | YES  |     | NULL    |                |
| created_at | datetime     | YES  |     | NULL    |                |
| updated_at | datetime     | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

一つ前のバージョンに戻す

rake db:rollback

戻した後

>||
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| hoge       | varchar(255) | YES  |     | NULL    |                |
| created_at | datetime     | YES  |     | NULL    |                |
| updated_at | datetime     | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

|