【发布时间】:2018-01-31 05:39:36
【问题描述】:
我正在使用 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 语句中创建唯一索引的正确方法是什么?
【问题讨论】:
-
user_id列是否保留在user_notifications表中?检查UserNotification.column_names -
我不明白你的问题。我在“create table”下面有这个“t.references:users, index: true, on_delete::cascade”,所以不应该创建一个“user_id”列吗?
-
当我运行上述迁移时,它失败并且没有创建 user_notifications 表。我看到语句“create_table(:user_notifications)”,然后是“rake aborted!StandardError:发生错误,这个和所有以后的迁移都取消了:”,然后是我上面发布的错误。
标签: ruby-on-rails postgresql migration rake ruby-on-rails-5