shou.com
JP / EN

Railsで使うカラムのあれこれ

Tue May 22, 2018
Tue May 22, 2018

既存のカラムを変更する

1
2
$ rails g migration change_カラム名_to_テーブル名
ex) rails g migration change_age_to_users
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class ChangeColumnToUsers < ActiveRecord::Migration
 # 変更内容
 def up
  change_column :age, :integer, null:false, default:
 end
 # 変更前の状態
 def down
  change_column :age, :integer, null:false
 end
end

カラムを削除する

1
2
$ rails g migration remove_カラム名_to_テーブル名 カラム名
例:($ rails g migration remove_age_to_users age)

カラムの追加

1
2
$ rails g migration Addカラム名Toテーブル名 カラム名:型名
例:($ rails g migration AddAgeToUsers age:integer)

あとは、いつものように、

1
$ rake db:migrate
See Also