15

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.

yoshyosh
  • 13,956
  • 14
  • 38
  • 46

3 Answers3

14

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

remove_index :units, :column => :lesson_id
Kris
  • 2,108
  • 18
  • 19
  • thanks :D, seems like you guys have slightly different answers – yoshyosh May 24 '11 at 09:35
  • The difference is that Yule gives a name to the index in his self.up which he uses for removing it. The code I provided removes the index based on its column name. – Kris May 24 '11 at 09:39
10

Almost

class AddIndexToUnits < ActiveRecord::Migration
  def self.up
    add_index :units, :lesson_id, :name=>'lesson_index'
  end

  def self.down
    remove_index :units, 'lesson_index'
  end
end
Yule
  • 9,668
  • 3
  • 51
  • 72
  • thanks! :) how do I add this from the command line: rails generate migration add_index_to_units doesn't work – yoshyosh May 24 '11 at 09:34
  • What exactly does not work? A new migration file is not created? – Arsen7 May 24 '11 at 09:37
  • a file is created but it looks really weird... like has 2 add_columns in the self.up definition – yoshyosh May 24 '11 at 09:46
  • @Arsen I'm not sure you can do this directly from command line. Is there a reason you can't just edit migration file? If not checkout https://github.com/capotej/migration_for. Seems to do what you're after... – Yule May 24 '11 at 09:55
2

To remove an index, you must use remove_index with the same table and column specification as the self.up's add_index has. So:

def self.down
  remove_index :units, :lesson_id
end

A multi-column index example would be:

def self.down
  remove_index :units, [:lesson_id, :user_id]
end
Laas
  • 5,978
  • 33
  • 52