Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to add add_index to existing table

I already migrated a table called units with several columns. I was wondering how to migrate in a stand alone 'add_index' to this table using the cmd. Is this code correct:

class AddIndexToUnits < ActiveRecord::Migration
  def self.up
    add_index :units, :lesson_id
  end

  def self.down
    remove :units
  end
end

I have a feeling the self.down could be wrong, I am unsure.

like image 272
yoshyosh Avatar asked May 24 '11 09:05

yoshyosh


People also ask

What is ADD index in rails?

An index is used to speed up the performance of queries on a database. Rails allows us to create index on a database column by means of a migration. By default, the sort order for the index is ascending. But consider the case where we are fetching reports from the database.

How do I rollback migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.


1 Answers

The self.up method is correct. Use this for your self.down:

remove_index :units, :column => :lesson_id
like image 185
Kris Avatar answered Oct 13 '22 07:10

Kris