【问题标题】:migration to add index when column is already exists in db rails?当 db rails 中已存在列时迁移以添加索引?
【发布时间】:2014-08-22 04:07:22
【问题描述】:

当我的数据库中已经存在列时如何添加索引?

当我像这样创建迁移时:

class AddIndexToUsers < ActiveRecord::Migration
  def change
    remove_column :users, :id_number if index_exists?(:id_number)
    add_column :users, :id_number, :string
    add_index :users, :id_number, unique: true
  end
end

创建具有相同 id_number 的对象时出现这样的错误:

SQLite3::ConstraintException: column id_number is not unique: INSERT INTO "users" ("bank_account", "birth_date", "confirmed", "confirmed_at", "created_at", "credit_card_id", "email", "encrypted_password", "facebook_id", "google_id", "id_issuing_country", "id_number", "last_name", "name", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

【问题讨论】:

  • 您添加了唯一索引 - 您认为尝试插入重复的 id_number 时会发生什么?

标签: ruby-on-rails validation model uniq


【解决方案1】:
class AddIndexToUsers < ActiveRecord::Migration
 def change
  remove_index :users, :id_number if index_exists?(:id_number)
  add_index :users, :id_number, unique: true
  end
end

如果您已经在 :users 表中重复了 id_number 条目,则此操作将失败。如果有,您必须先删除重复项

【讨论】:

    【解决方案2】:

    仔细考虑您的问题...为什么要添加已经存在的内容?如果你想在关系数据库中生成一个模型并且没有ID,你需要传入:id => false

    create_table(:categories_suppliers, id: false) do |t|
      t.column :category_id, :integer
      t.column :supplier_id, :integer
    end
    

    如果你弄错了,并且你试图确保你的模型有一个 ID,你可以去你的终端并输入 rails c 来测试

    @users = User.all
    @users.first.id
    

    要验证这一点,您需要在表中实际包含一些数据。当然,您会知道,因为在终端中输入 @users 会返回一个空数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-17
      • 2014-05-13
      • 2012-11-18
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2019-10-22
      • 2015-03-01
      相关资源
      最近更新 更多