ruby-on-rails - 如何在 Rails 中创建可逆迁移助手?

标签 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')
  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/

相关文章:

ruby-on-rails - rails : Prevent parent model from being created and surfacing child model validation errors

ruby - Ruby 中 yield 和 return 的使用

ruby-on-rails - 连接两个字段 activerecord

ruby - 为什么我会收到 HABTM 协会的 Unpermitted parameters?

迁移应用程序中缺少 django 1.9 models_module

android - 如何在一个应用程序中处理 SQLiteOpenHelper 和 RoomDatabase?

ruby-on-rails - 如何将 ruby​​ 散列数组转换为单个散列?

ruby-on-rails - 使用 Chartkick 添加注释

ruby-on-rails - 在 `includes` 急切加载上重用范围作为过滤器

Swift 3 - 错误 - 无法使用类型为 'data' 的参数列表调用 '(using: String.Encoding)'