如何从Rails中的数据库列中删除唯一约束?

时间:2022-11-24 21:55:13

I created a table using the following migration:

我使用以下迁移创建了一个表:

class CreateProfilePictures < ActiveRecord::Migration
  def change
    create_table :profile_pictures do |t|
      t.integer :user_id, null: false
      t.integer :picture_id, null: false
      t.timestamps null: false
    end

    add_index :profile_pictures, :user_id, unique: true
    add_index :profile_pictures, :picture_id, unique: true
  end
end

I tried to remove the constraint with the following:

我尝试使用以下内容删除约束:

class FixProfilePic < ActiveRecord::Migration
  def change
    change_column :profile_pictures, :picture_id, :integer, unique: false
  end
end

I still get a unique constraint violation error if I try to use the same picture_id in more than one place. What is the proper way to remove the uniqueness constraint from picture_id?

如果我尝试在多个地方使用相同的picture_id,我仍然会遇到唯一的约束违规错误。从picture_id中删除唯一性约束的正确方法是什么?

2 个解决方案

#1


29  

You must remove your index with:

您必须删除索引:

remove_index :profile_pictures, :picture_id

add add it again with:

添加再次添加:

add_index :profile_pictures, :picture_id

ActiveRecord::Migration

ActiveRecord的::迁移

#2


6  

add_index :profile_pictures, :picture_id, unique: true

add_index:profile_pictures,:picture_id,unique:true

So update your index to:

所以将索引更新为:

  remove_index :profile_pictures, :picture_id
  add_index :profile_pictures, :picture_id

I'm guessing this is it.

我猜这就是它。

#1


29  

You must remove your index with:

您必须删除索引:

remove_index :profile_pictures, :picture_id

add add it again with:

添加再次添加:

add_index :profile_pictures, :picture_id

ActiveRecord::Migration

ActiveRecord的::迁移

#2


6  

add_index :profile_pictures, :picture_id, unique: true

add_index:profile_pictures,:picture_id,unique:true

So update your index to:

所以将索引更新为:

  remove_index :profile_pictures, :picture_id
  add_index :profile_pictures, :picture_id

I'm guessing this is it.

我猜这就是它。