LoginSignup
1
1

More than 3 years have passed since last update.

既存のテーブルに外部キー(ナントカid)を追加する

Last updated at Posted at 2019-09-07

3行で

  • ターミナルにコマンドを書いてmigrationファイルを作る
  • migrationファイルの中身を確認する
  • rails db:migrate

くわしく

今回の場合、itemsテーブルuserの外部キーであるuser_idを追加したい。

$ rails g migration AddUserToItems user:references

実行するとmigrationファイルが作られる。

作成されたmigrationファイル
class AddUserToItems < ActiveRecord::Migration[5.2]
  def change
    add_reference :items, :user, foreign_key: true
  end
end

問題なければ下記のコマンドを入力する。

$ rails db:migrate
1
1
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
1
1