代码之家  ›  专栏  ›  技术社区  ›  Dave

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

  •  4
  • Dave  · 技术社区  · 7 年前

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

    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语句中创建唯一索引的正确方法是什么?

    2 回复  |  直到 7 年前
        1
  •  11
  •   Pavan Cesar    7 年前

    PG::未定义列:错误:“user\u id”列不存在

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

    解决方案:

    把它改成 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
    
        2
  •  0
  •   itsnikolay    7 年前

    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