我发现自己必须在 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
但这样做是为了让变化是“可逆的”,这让我不知所措。
最佳答案
这似乎不是官方支持的方式,因此您可能需要打开类 ActiveRecord::Migration::CommandRecorder
并记录新方法及其反转版本。
在 activerecord/lib/active_record/migration/command_recorder.rb 找到类的定义.
关于ruby-on-rails - 如何在 Rails 中创建可逆迁移助手?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16983177/