LoginSignup
0
0

More than 3 years have passed since last update.

データの入ったテーブルに対して外部キーが設定されたカラムを追加する

Posted at

やりたいこと

foosテーブルとbarsテーブルがあったとして
barsテーブルにfoo:referencesのカラムを追加したい。
ただし、システムは運用を始めておりbarsテーブルにはデータが入っている。

普通に

db/migrate/YYYYMMDDhhmmss_add_foo_to_bars.rb
class AddFooToBars < ActiveRecord::Migration[6.0]
  def change
    add_reference :bars, :foo, null: false, foreign_key: true
  end
end

db:migrateしようとすると、空のfoo_idカラムが発生してしまうため、エラーになってしまう。

解決策

まずは初期値を設定してカラムを追加する。
default値はfoosテーブルに存在するidを指定する。

db/migrate/YYYYMMDDhhmmss_add_foo_to_bars.rb
class AddFooToBars < ActiveRecord::Migration[6.0]
  def change
    add_reference :bars, :foo, null: false, foreign_key: true, default: 1
  end
end

次にDEFAULTの定義を残しておくと気持ち悪いので消す。

db/migrate/YYYYMMDDhhmmss_change_foo_to_bars.rb
class ChangeFooToBars < ActiveRecord::Migration[6.0]
  def change
    change_column_default(:bars, :foo_id, nil)
  end
end

これでデータの入ったテーブルに外部キーが設定されたカラムを追加できます。

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