LoginSignup
12
12

More than 5 years have passed since last update.

ActiveRecordのActiveRecord::PendingMigrationErrorを無視する

Posted at

Railsは未適用のマイグレーションを見つけると ActiveRecord::PendingMigrationErrorを投げる。
基本的に便利なんだけど、たまーにこのチェック機構を無効化したいことがあるのでメモしておく。

未適用のマイグレーションのチェック機構を無効化する

Configuring Rails Applicationsには載っていないけれど、次の方法で無視できる。

config/environments/development.rb
config.active_record.migration_error = false

ソース

ActiveRecord::Migration::CheckPending のコメントに設定方法がある。

4-2-stable/activerecord/lib/active_record/migration.rb
    # This class is used to verify that all migrations have been run before
    # loading a web page if config.active_record.migration_error is set to :page_load
    class CheckPending
      def initialize(app)
        @app = app
        @last_check = 0
      end

      def call(env)
        if connection.supports_migrations?
          mtime = ActiveRecord::Migrator.last_migration.mtime.to_i
          if @last_check < mtime
            ActiveRecord::Migration.check_pending!(connection)
            @last_check = mtime
          end
        end
        @app.call(env)
      end

      private

      def connection
        ActiveRecord::Base.connection
      end
    end

初期化はこんな感じ

4-2-stable/activerecord/lib/active_record/railtie.rb
    initializer "active_record.migration_error" do
      if config.active_record.delete(:migration_error) == :page_load
        config.app_middleware.insert_after "::ActionDispatch::Callbacks",
          "ActiveRecord::Migration::CheckPending"
      end
    end

蛇足:スマートじゃない方法

最初はこんなコードを使ってた。

config/initializers/skip_activerecord_migration_check_pending.rb
Rails.application.config.middleware.delete 'ActiveRecord::Migration::CheckPending'
12
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12