8
3

カラムの追加、削除

Posted at

1. カラムの追加

$ rails g migrationでmigrationファイルを作成する。
例えば、usersテーブルにageカラムを追加する場合、以下のようにコマンドを実行する。

$ rails g migration AddAgeToUsers age:integer

生成されたmigrationファイルは以下のようになる。

class AddAgeToUsers < ActiveRecord::Migration
  def change
    add_column :users, :age, :integer
  end
end

データベースに反映。

$ rails db:migrate

2. カラムの削除

不要になったカラムを削除する場合も、同様にmigrationファイルを作成する。
例えば、usersテーブルからageカラムを削除するには、以下のコマンドを実行する。

rails g migration RemoveAgeFromUsers age:integer

生成されたmigrationファイルは以下のようになる。

class RemoveAgeFromUsers < ActiveRecord::Migration
  def change
    remove_column :users, :age, :integer
  end
end

カラム追加時と同様に$ rails db:migrateコマンドを実行して変更を反映させる。

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3