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.

3 Answers 3

14

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

remove_index :units, :column => :lesson_id
Sign up to request clarification or add additional context in comments.

2 Comments

thanks :D, seems like you guys have slightly different answers
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.
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

4 Comments

thanks! :) how do I add this from the command line: rails generate migration add_index_to_units doesn't work
What exactly does not work? A new migration file is not created?
a file is created but it looks really weird... like has 2 add_columns in the self.up definition
@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 github.com/capotej/migration_for. Seems to do what you're after...
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.