Search code examples
postgresqlreferencemigrationuniqueruby-on-rails-5

What's the proper way to add an index to a table in a Rails migration?


I'm using Rails 5 with PostGres 9.5 . I have the following migration

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

Upon running the migration, it is dying with this error

PG::UndefinedColumn: ERROR:  column "crypto_currency" does not exist

What is the proper way to add the index? The table name that I want to reference is called "crypto_currencies".


Solution

  •  add_index 'crypto_index_currencies', ['crypto_currency'], name: "index_crypto_index_currencies_on_crypto_currency", unique: true, using: :btree
    

    using: :btree its optional.