在Rails迁移中向表中添加索引的正确方法是什么?
问题描述:
我正在使用Rails 5和PostGres 9.5。我有以下迁移在Rails迁移中向表中添加索引的正确方法是什么?
class CreateCryptoIndexCurrencies < ActiveRecord::Migration[5.0]
def change
create_table :crypto_index_currencies do |t|
t.references :crypto_currency, foreign_key: true
t.date :join_date, :null => false, :default => Time.now
t.timestamps
end
add_index :crypto_index_currencies, :crypto_currency, unique: true
end
end
在运行迁移,这是死亡与此错误
PG::UndefinedColumn: ERROR: column "crypto_currency" does not exist
什么是添加索引的正确方法?我想引用的表名称为“crypto_currencies”。
答
add_index 'crypto_index_currencies', ['crypto_currency'], name: "index_crypto_index_currencies_on_crypto_currency", unique: true, using: :btree
内的语法::B树其可选的。
答
这是添加它使用CREATE_TABLE块
class CreateCryptoIndexCurrencies < ActiveRecord::Migration[5.0]
def change
create_table :crypto_index_currencies do |t|
t.references :crypto_currency, foreign_key: true
t.date :join_date, :null => false, :default => Time.now
t.index :crypto_currency, unique: true
end
end
end