我在 Rails 之外使用 ActiveRecord。我想要一个程序来生成迁移的框架(以及一个收集和维护它们的系统)。
任何人都可以提出建议吗?
还要看看新的active_record_migrations
有一个 gem 可以在非 Rails 项目中使用 Rails 数据库迁移。它的名字是“standalone_migrations”
这是一个链接
如果您不喜欢使用 rake,但仍然获得 ActiveRecord::Migration 的系统部分,那么您可以使用以下内容来处理普通 ruby 的起伏(没有任何轨道):
require 'active_record'
require 'benchmark'
# Migration method, which does not uses files in db/migrate but in-memory migrations
# Based on ActiveRecord::Migrator::migrate
def migrate(migrations, target_version = nil)
direction = case
when target_version.nil?
:up
when (ActiveRecord::Migrator::current_version == target_version)
return # do nothing
when ActiveRecord::Migrator::current_version > target_version
:down
else
:up
end
ActiveRecord::Migrator.new(direction, migrations, target_version).migrate
puts "Current version: #{ActiveRecord::Migrator::current_version}"
end
# MigrationProxy deals with loading Migrations from files, we reuse it
# to create instances of the migration classes we provide
class MigrationClassProxy < ActiveRecord::MigrationProxy
def initialize(migrationClass, version)
super(migrationClass.name, version, nil, nil)
@migrationClass = migrationClass
end
def mtime
0
end
def load_migration
@migrationClass.new(name, version)
end
end
# Hash of all our migrations
migrations = {
2016_08_09_2013_00 =>
class CreateSolutionTable < ActiveRecord::Migration[5.0]
def change
create_table :solution_submissions do |t|
t.string :problem_hash, index: true
t.string :solution_hash, index: true
t.float :resemblance
t.timestamps
end
end
self # Necessary to get the class instance into the hash!
end,
2016_08_09_2014_16 =>
class CreateProductFields < ActiveRecord::Migration[5.0]
# ...
self
end
}.map { |key,value| MigrationClassProxy.new(value, key) }
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => 'XXX.db'
)
# Play all migrations (rake db:migrate)
migrate(migrations, migrations.last.version)
# ... or undo them (rake db:migrate VERSION=0)
migrate(migrations, 0)
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class SolutionSubmission < ApplicationRecord
end
我做了一个最小的例子来说明如何在 Rails 之外使用活动记录。非 Rails(和非 Ruby)项目中的 Rails 迁移(独立迁移)。
https://github.com/euclid1990/rails-migration
(支撑导轨 >= 5.2)
你可以在这个 repo 中引用 Rake 文件。
还有另一个 gem 叫做otr-activerecord。此 gem 提供以下任务:
rake db:create
rake db:create_migration[name]
rake db:drop
rake db:environment:set
rake db:fixtures:load
rake db:migrate
rake db:migrate:status
rake db:rollback
rake db:schema:cache:clear
rake db:schema:cache:dump
rake db:schema:dump
rake db:schema:load
rake db:seed
rake db:setup
rake db:structure:dump
rake db:structure:load
rake db:version
您需要做的就是安装它并添加Rakefile
内容
load 'tasks/otr-activerecord.rake'
OTR::ActiveRecord.configure_from_file! 'config/database.yml'
我更喜欢这个 gem 而不是active_record_migrations
Standalone Migration 因为这两个 gem 依赖于railties
几乎整个 Rails。例如,Nokogiri 编译需要很长时间,并且占用大量空间。