LoginSignup
0
0

More than 1 year has passed since last update.

referencesを使用した外部キーに、あとからUnique属性を設定する

Last updated at Posted at 2021-11-11

Postテーブルを作成し、userテーブルを外部参照にした。
しかし、あとからuser_idをユニークにしたくなった。

xxxxxxxxxxxxxx_create_posts.rb
class CreatePosts < ActiveRecord::Migration[6.1]
  def change
    enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
    create_table :posts, id: :uuid do |t|
      t.references :user, type: :uuid, null: false, foreign_key: true
      t.timestamps
    end
  end
end

※ポスグレで、idをuuidにしています。

あとからユニーク制約をつけたい

成功した例

indexを一旦削除してから、unique属性をつけたindexを追加する。

xxxxxxxxxxxxxx_add_index_user_id_to_posts.rb
class AddIndexUserIdToPosts < ActiveRecord::Migration[6.1]
  def change
    remove_index :posts, :user_id
    add_index :posts, :user_id, unique: true
  end
end

失敗した例

xxxxxxxxxxxxxx_add_index_user_id_to_posts.rb
class AddIndexUserIdToPosts < ActiveRecord::Migration[6.1]
  def change
    add_index :posts, :user_id, unique: true
  end
end

これだと、以下のように「もうindexがあるからダメだよ」と言われてしまう。

PG::DuplicateTable: ERROR:  relation "index_posts_on_user_id" already exists
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