加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在rails中创建可逆迁移帮助程序?

发布时间:2020-12-17 02:34:39 所属栏目:百科 来源:网络整理
导读:我发现自己必须在rails应用程序的几个表上执行非常相似的sql语句(除了表名之外可能有1个参数).结果,我得到了很多类似的迁移,就像这样: class DoSomeSQLOnUser ActiveRecord::Migration def up execute('some long sql that alters the user.field1') execut
我发现自己必须在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,: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找到该类的定义.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读