0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

カラムから外部キーを削除する

Last updated at Posted at 2021-03-08

アプリを作成している中で外部キーを削除する必要が出てきたので今後のためにも記事を残します。

/schema.rb

 create_table "behavior_histories", force: :cascade do |t|
    t.bigint "care_recipitent_id"
    t.date "behavior_history_date", null: false
    t.text "action_record", null: false
    t.time "behavior_time", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.bigint "family_id"
    t.index ["family_id"], name: "index_behavior_histories_on_family_id"
    t.index ["care_recipitent_id"], name: "index_behavior_histories_on_care_recipitent_id"

この中の外部キーであるcare_recipitent_idを削除します。

###migrationファイルの作成

rails g migration remove_foreign_key_to_behavior_histories

###外部キーの削除

class RemoveForeignKeyToBehaviorHistories < ActiveRecord::Migration[6.0]
  def change
    remove_foreign_key :behavior_histories, :care_recipitents
    remove_reference :behavior_histories, :care_recipitent, index: true
  end
end

rails:db:mirateで削除されていることを無事確認。
※remove_foreign_keyとremove_referenceの順序を変えるとうまくいかないため注意してください。

###外部キーを追加したい場合

class AddReferencesToAddresses < ActiveRecord::Migration[6.0]
  def change
    add_reference :addresses, :family, foreign_key: true
  end
end

参考:references型のカラムを後から追加・削除

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?