加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在Rails创建表迁移中创建唯一索引?

发布时间:2020-12-17 02:57:08 所属栏目:百科 来源:网络整理
导读:我正在使用Rails 5和PostgreSQL 9.5.如何在表格中创建唯一索引?我想从两列中创建唯一索引,这两列本身就是对其他表的引用.所以我试过了 class CreateUserNotificationsTable ActiveRecord::Migration[5.0] def change create_table :user_notifications do |
我正在使用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,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_id而不是user_id的列,因此它无法使用t.index [:user_id,:crypto_currency_id]创建索引,唯一: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,on_delete: :cascade
      t.references :crypto_currency,unique: true
    end
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读