我如何在Rails中创建一个可逆迁移助手?

5

我发现自己在Rails应用程序上需要执行非常相似的SQL语句(除了表名之外可能还有1个参数)。因此,我得到了许多看起来很相似的迁移,例如:

class DoSomeSQLOnUser < ActiveRecord::Migration
  def up
    execute('some long sql that alters the user.field1')
    execute('some long sql that alters the user.field2')
  end

  def down
    execute('some sql that undoes the changes')
  end
end

我还需要同样的东西用于客户、销售等等。

我想扩展ActiveRecord::Migration,以便我可以使用以下方式:

class DoSomeSQLOnUser < ActiveRecord::Migration
  def change
    do_custom_thing_on :users, :field1
    do_custom_thing_on :users, :field2
  end
end

我该怎么做?当操作分为上下两部分时,我认为我知道如何做到这一点,就像这样:

class DoSomeSQLOnUser < ActiveRecord::Migration
  def up
    do_custom_thing_on :users, :field1
    do_custom_thing_on :users, :field2
  end
  def down
    undo_custom_thing_on :users, :field1
    undo_custom_thing_on :users, :field2
  end
end

但是让这种改变“可逆”对我来说很难理解。

4个回答

2

2
在Rails 4中,有一个可逆的辅助方法,可以像这样使用:
def change
  do_custom_thing_on :users, :field1
  do_custom_thing_on :users, :field2
end

def do_custom_thing_on(table, field)
  reversible do |dir|
    dir.up { execute "some long sql to alter #{field} on #{table}"}
    dir.down { execute "some long sql to undo #{field} on #{table}"}
  end
end

1

0
更改方法的主要目的是添加、重命名列,而不是删除列。更改方法“知道”如何在回滚迁移时进行反向操作。因此,如果您想做一些不涉及删除的操作,只需在更改方法中执行即可,ActiveRecord会自动将其反转,我认为。

您可以从官方文档中获取更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接