LoginSignup
2
0

More than 5 years have passed since last update.

Ruby on Railsでデータベースにカラムを追加する手順【マイグレーションファイル】

Last updated at Posted at 2019-03-25

はじめに

ruby on rails 5.0でDBにカラムを追加する方法です。
progateをやっていて中々覚えられなかったので超簡潔にまとめました。

手順

1. マイグレーションファイルの作成
2. マイグレーションファイルの編集
3. マイグレーションファイルのchangeメソッドの実行

1. まずはマイグレーションファイルの作成

マイグレーションファイルとは...DBのテーブルの設計書

$ rails g migration [ファイル名]

具体的には意図が分かる、かつ、_を入れて小文字のみでファイル名を決定する。

rails g migration add_password_to_users

2. 次にマイグレーションファイルの編集

/db/migrate内に生成されたマイグレーションファイルのchangeメソッドに以下のように記述します。

/db/migrate/migration_file.rb
class [自動生成されるクラス名] < ActiveRecord::Migration[5.0]
  def change
    add_column :[テーブル名], :[カラム名], :[データ型]
  end
end

具体的にはこんな感じ。

/db/migrate/20190325~~~~~~add_password_to_users.rb
class AddPasswordToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :password, :string
  end
end

3. 最後にマイグレーションファイルのchangeメソッドの実行

$ rails db:migrate

終わりに

参考にしたqiita記事

マイグレーションファイルとスキーマファイルについて(migration, schema, rake)
マイグレーションファイルの役割と生成

2
0
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
2
0