跳到内容 跳到搜索

迁移上下文

MigrationContext 设置迁移运行的上下文。

迁移上下文需要在 migrations_paths 参数中设置迁移路径。还可以选择提供 schema_migration 类。多个数据库应用程序将为每个数据库实例化一个 SchemaMigration 对象。在 Rake 任务中,Rails 将为您处理此操作。

方法
M
N

属性

[R] internal_metadata
[R] migrations_paths
[R] schema_migration

类公有方法

new(migrations_paths, schema_migration = nil, internal_metadata = nil)

# File activerecord/lib/active_record/migration.rb, line 1205
    def initialize(migrations_paths, schema_migration = nil, internal_metadata = nil)
      if schema_migration == SchemaMigration
        ActiveRecord.deprecator.warn(<<-MSG.squish)
          SchemaMigration no longer inherits from ActiveRecord::Base. If you want
          to use the default connection, remove this argument. If you want to use a
          specific connection, instantiate MigrationContext with the connection's schema
          migration, for example `MigrationContext.new(path, Dog.connection.schema_migration)`.
        MSG

        schema_migration = nil
      end

      if internal_metadata == InternalMetadata
        ActiveRecord.deprecator.warn(<<-MSG.squish)
          SchemaMigration no longer inherits from ActiveRecord::Base. If you want
          to use the default connection, remove this argument. If you want to use a
          specific connection, instantiate MigrationContext with the connection's internal
          metadata, for example `MigrationContext.new(path, nil, Dog.connection.internal_metadata)`.
        MSG

        internal_metadata = nil
      end

      @migrations_paths = migrations_paths
      @schema_migration = schema_migration || SchemaMigration.new(connection)
      @internal_metadata = internal_metadata || InternalMetadata.new(connection)
    end

实例公有方法

migrate(target_version = nil, &block)

migrations_path 中运行迁移。

如果 target_versionnilmigrate 将运行 up

如果架构中的 current_versiontarget_version 均为 0,则将返回一个空数组,并且不会运行任何迁移。

如果架构中的 current_version 大于 target_version,则将运行 down

如果未满足任何条件,则将使用 target_version 运行 up

# File activerecord/lib/active_record/migration.rb, line 1246
def migrate(target_version = nil, &block)
  case
  when target_version.nil?
    up(target_version, &block)
  when current_version == 0 && target_version == 0
    []
  when current_version > target_version
    down(target_version, &block)
  else
    up(target_version, &block)
  end
end