5

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

しかし、変更が「可逆」になるようにすると、私は逃げます。

4

4 に答える 4

2

これは公式にサポートされている方法ではないようです。そのため、おそらくクラスを開いてActiveRecord::Migration::CommandRecorder、新しいメソッドとその反転バージョンを記録する必要があります。

クラスの定義をactiverecord/lib/active_record/migration/command_recorder.rbで見つけます。

于 2013-06-07T11:52:44.693 に答える