【发布时间】:2016-05-18 12:25:08
【问题描述】:
我是一名新手 ruby 程序员,正在研究 rails api。问题是 api 正在生产中,现在我想向模型中的一列添加唯一约束。目前允许重复条目,我想让该列唯一。
所以我添加了两个同名的灯具:
two:
name: MyString2
location:
status: 2
three:
name: MyString2
location:
status: 1
然后我尝试像这样运行迁移:
class AddUniqueToLocationColumnName < ActiveRecord::Migration
class User < ActiveRecord::Base
end
def self.up
remove_index :locations, column: :name
add_index :locations, :name, unique: true
end
def self.down
remove_index :locations, column: :name # remove unique index
add_index :locations, :name # adds just index, without unique
end
end
但它显示错误:“数据库中存在重复项。迁移失败。” 同样是问题。我已经在生产表中有重复项。我想为表 "locations" 中的列 "name" 添加一个唯一约束。我怎样才能使这个专栏独一无二?
【问题讨论】:
-
这是b'coz重复记录存在于数据库中,首先从数据库中删除重复记录然后尝试运行。
-
我想通过迁移删除它。通过 ruby 代码找到所有重复项并销毁它们
标签: ruby-on-rails ruby migration