Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the index of the table that was already created using rails migration?

I already have this migration file that was created and the migration was run.

class CreateStudentContexts < ActiveRecord::Migration
  def change
    create_table :student_contexts do |t|
      t.string :student_id, index: true, null: false, limit: 40
      t.text :data
      t.timestamps null: false

      t.index [:student_id, :updated_at], unique: true, name: 'student_context_index'
    end
  end
end

Now i want to create a new migration file that will update the index, and the index fields should be student_id and created_at.

like image 457
Lollypop Avatar asked Dec 13 '25 23:12

Lollypop


2 Answers

This question is kinda old, but in case anyone comes across it:

Justin Wood's answer should work, but with one change: replace the column name in the remove_index method with the name of the index:

remove_index :student_contexts, name: 'student_context_index'

When the index was created, it was given a specific (non-standard) name with the name argument, so you also need to use the name argument in the remove_index statement. Otherwise, Rails expects the index to have a standard name (in this case "index_student_contexts_on_updated_at").

like image 173
dbdb Avatar answered Dec 15 '25 13:12

dbdb


You can create another migration and change the table. Something like

class MyMigration < ActiveRecord::Migration
  def change
    remove_index :student_contexts, :updated_at
    add_index :student_contexts, :created_at
  end
end

would do.

like image 32
Justin Wood Avatar answered Dec 15 '25 12:12

Justin Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!