【问题标题】:What's the proper way to add an index to a table in a Rails migration?在 Rails 迁移中向表添加索引的正确方法是什么?
【发布时间】:2017-07-28 15:01:04
【问题描述】:

我正在使用带有 PostGres 9.5 的 Rails 5。我有以下迁移

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”。

【问题讨论】:

    标签: postgresql reference migration unique ruby-on-rails-5


    【解决方案1】:
     add_index 'crypto_index_currencies', ['crypto_currency'], name: "index_crypto_index_currencies_on_crypto_currency", unique: true, using: :btree
    

    使用: :btree 是可选的。

    【讨论】:

      【解决方案2】:

      这是在 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-20
        • 2020-05-23
        • 1970-01-01
        • 1970-01-01
        • 2020-04-10
        • 1970-01-01
        • 1970-01-01
        • 2021-12-04
        相关资源
        最近更新 更多