如何在 Rails create table 迁移中创建唯一索引?

How do I create a unique index within a Rails create table migration?

我正在使用 Rails 5 和 PostgreSQL 9.5。如何在 table 中创建唯一索引?我想从两列中创建唯一索引,它们本身是对其他 table 的引用。所以我尝试了

class CreateUserNotificationsTable < ActiveRecord::Migration[5.0]
  def change
    create_table :user_notifications do |t|
      t.references :users, index: true, on_delete: :cascade
      t.references :crypto_currencies, index: true, on_delete: :cascade
      t.integer  "price",      null: false
      t.boolean "buy",      null: false
      t.index [:user_id, :crypto_currency_id], unique: true
    end
  end
end

但我遇到了错误

PG::UndefinedColumn: ERROR:  column "user_id" does not exist
: CREATE UNIQUE INDEX  "index_user_notifications_on_user_id_and_crypto_currency_id" ON "user_notifications"  ("user_id", "crypto_currency_id")
/Users/davea/.rvm/gems/ruby-2.4.0/gems/activerecord-5.0.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:98:in `async_exec'
/Users/davea/.rvm/gems/ruby-2.4.0/gems/activerecord-5.0.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:98:in `block in execute'
/Users/davea/.rvm/gems/ruby-2.4.0/gems/activerecord-5.0.4/lib/active_record/connection_adapters/abstract_adapter.rb:590:in `block in log'

在 create table 语句中创建唯一索引的正确方法是什么?

PG::UndefinedColumn: ERROR: column "user_id" does not exist

问题是 t.references :users 创建了一个名为 users_id 而不是 user_id 的列,因此它无法创建一个索引 t.index [:user_id, :crypto_currency_id], unique: true 作为列 user_id未创建导致该错误。

解法:

改成t.references :user就可以了。 t.references :crypto_currencies 也是如此。

class CreateUserNotificationsTable < ActiveRecord::Migration[5.0]
  def change
    create_table :user_notifications do |t|
      t.references :user, index: true, on_delete: :cascade
      t.references :crypto_currency, index: true, on_delete: :cascade
      t.integer  "price",      null: false
      t.boolean "buy",      null: false
      t.index [:user_id, :crypto_currency_id], unique: true
    end
  end
end

尝试提取 create_table 方法的索引,例如:

class CreateUserNotificationsTable < ActiveRecord::Migration[5.0]
  def change
    create_table :user_notifications do |t|
      t.references :users, index: true, on_delete: :cascade
      t.references :crypto_currencies, index: true, on_delete: :cascade
      t.integer  "price",      null: false
      t.boolean "buy",      null: false
    end

    add_index :user_notifications, [:user_id, :crypto_currencies_id], unique: true
  end
end