我发现自己在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
但是让这种改变“可逆”对我来说很难理解。