kik*_*ito 5 ruby migration ruby-on-rails
我发现自己必须在 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
Run Code Online (Sandbox Code Playgroud)
然后我对客户,销售等也有同样的事情。
我想扩展ActiveRecord::Migration以便我可以这样做:
class DoSomeSQLOnUser < ActiveRecord::Migration
def change
do_custom_thing_on :users, :field1
do_custom_thing_on :users, :field2
end
end
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我想我知道当操作分为上下时怎么做,像这样:
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
Run Code Online (Sandbox Code Playgroud)
但是这样做是为了使变化是“可逆的”,这让我望而却步。
小智 2
这似乎不是官方支持的方法,因此您可能需要打开该类ActiveRecord::Migration::CommandRecorder并记录新方法及其反转版本。
在activerecord/lib/active_record/migration/command_recorder.rb中找到该类的定义。
| 归档时间: |
|
| 查看次数: |
602 次 |
| 最近记录: |