【问题标题】:Adding unique constraint through migration not working通过迁移添加唯一约束不起作用
【发布时间】: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'co​​z重复记录存在于数据库中,首先从数据库中删除重复记录然后尝试运行。
  • 我想通过迁移删除它。通过 ruby​​ 代码找到所有重复项并销毁它们

标签: ruby-on-rails ruby migration


【解决方案1】:

所以您不希望您的位置模式中的任何两个条目有任何重复的名称,但重复项已经存在?您必须通过以下任一方式删除重复项:

  1. 删除模型中的数据,重新开始

  2. 删除具有重复名称的各个位置

  3. 更改重复位置的名称。

所有这些都可以在 rails/heroku 控制台中轻松完成。

此外,您可以将此代码添加到您的位置模型中:

class Location < ActiveRecord::Base
   validates_presence_of :name
   validates_uniqueness_of :name
end

【讨论】:

  • 1.我不能从头开始,因为它正在生产中。 2. 单独删除很麻烦,因为有很多重复。 3. 名称不能更改。有没有其他方法可以像在迁移本身中编写几行代码这样可以删除重复项并添加唯一约束?
猜你喜欢
  • 1970-01-01
  • 2011-03-23
  • 2017-06-23
  • 2017-03-26
  • 2013-11-19
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
相关资源
最近更新 更多