Rails: How to add add_index to existing table

独自空忆成欢 提交于 2019-12-03 09:51:20

问题


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.


回答1:


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

remove_index :units, :column => :lesson_id



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/6108340/rails-how-to-add-add-index-to-existing-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!