15

我已经迁移了一个名为 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.down 可能是错误的,我不确定。

4

3 回答 3

14

self.up 方法是正确的。将其用于您的 self.down:

remove_index :units, :column => :lesson_id
于 2011-05-24T09:29:44.170 回答
10

几乎

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
于 2011-05-24T09:31:12.697 回答
2

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

def self.down
  remove_index :units, :lesson_id
end

多列索引示例是:

def self.down
  remove_index :units, [:lesson_id, :user_id]
end
于 2011-05-24T09:39:08.640 回答