How do I create a unique index within a Rails create table migration? How do I create a unique index within a Rails create table migration? postgresql postgresql

How do I create a unique index within a Rails create table migration?


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

The problem is t.references :users creates a column called users_id not user_id, so it unable to create an index with t.index [:user_id, :crypto_currency_id], unique: true as the column user_id is not created which resulted in that error.

Solution:

Just change it to t.references :user. Same goes for t.references :crypto_currencies too.

class CreateUserNotificationsTable < ActiveRecord::Migration[5.0]  def change    create_table :user_notifications do |t|      t.references :user, index: true, on_delete: :cascade      t.references :crypto_currency, 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  endend


Try to extract index of create_table method, like:

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    end    add_index :user_notifications, [:user_id, :crypto_currencies_id], unique: true  endend


The index name should be plural be for ID so your migration should be like that:

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      # users_id instead of user_id      t.index [:users_id, :crypto_currencies_id], unique: true    end  endend