Rails:如何将add_index添加到现有表

我已经迁移了一个名为units的表,其中有几列。 我想知道如何使用cmd将独立的“add_index”迁移到此表中。 这段代码是否正确:

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

我有一种感觉自我。可能是错的,我不确定。

self.up方法是正确的。 用于你的self.down:

 remove_index :units, :column => :lesson_id 

几乎

 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 

要删除索引,必须使用与self.up的add_index具有相同的表和列规范的add_index 。 所以:

 def self.down remove_index :units, :lesson_id end 

多列索引示例如下:

 def self.down remove_index :units, [:lesson_id, :user_id] end