Ruby on rails 如何在rails中创建可逆迁移帮助器?

Ruby on rails 如何在rails中创建可逆迁移帮助器?,ruby-on-rails,ruby,migration,Ruby On Rails,Ruby,Migration,我发现自己必须在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') en

我发现自己必须在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
我该怎么做?我想我知道当操作分为上下两部分时该怎么做,如下所示:

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
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
类DoSomeSQLOnUser
但是,这样做使更改“可逆”让我无法理解。

这样做似乎不是官方支持的方式,因此可能需要打开类
ActiveRecord::Migration::CommandRecorder
,并记录新方法及其反转版本


在中找到类的定义。

不确定是否需要执行其他操作,但至少应该向它正在添加的更改方法的主要目的添加一个反向自定义方法,重命名列但不删除。Change方法“知道”在回滚迁移时如何进行反转。所以,若你们想做一些事情,而不是删除,只需在change方法中进行,我认为ActiveRecord会自己反转它

您可以从Rails 4中的

获得更多信息,您可以这样使用:

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
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