Home > Blockchain >  When adding an index on multiple columsn in rails, two indexes are created. How do i prevent that?
When adding an index on multiple columsn in rails, two indexes are created. How do i prevent that?

Time:10-03

So I am currently assigned a task in Ruby which I have never used before and I've run into a very strange problem. I have this migration for a model message, which has an index on chat_id and number.

class CreateMessages < ActiveRecord::Migration[5.2]
  def change
    create_table :messages do |t|
      t.references :chat, foreign_key: true, null: false
      t.integer :number, null: false
      t.string :body
      #t.index [:chat_id, :number] doesn't work
      t.timestamps
    end
    #add_index :messages, [:chat_id, :number] #doesn't work either

  end
end

The end schema of both those migrations when running rails db:migrate is this

create_table "messages", force: :cascade do |t|
    t.integer "chat_id", null: false
    t.integer "number", null: false
    t.string "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["chat_id", "number"], name: "index_messages_on_chat_id_and_number"
    t.index ["chat_id"], name: "index_messages_on_chat_id"
  end

Obviously, the second created index is completely useless. How do I prevent this from occuring and create only one index when migrating?

Ruby 2.7.6 Rails 5.2.8.1

CodePudding user response:

This line is adding the index you wish to remove. It accepts an index parameter which defaults to true, change it to:

t.references :chat, foreign_key: true, null: false, index: false
  • Related