2012-08-09 84 views

回答

3

在非Rails項目中有一個使用Rails數據庫遷移的gem。它的名字是「standalone_migrations」

這裏是一個鏈接

https://github.com/thuss/standalone-migrations

+3

雖然這個鏈接可以回答這個問題,最好在這裏包含答案的重要部分,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – 2012-10-04 08:24:06

1

如果你不喜歡用耙,但仍獲得的系統的一部分ActiveRecord :: Migration,那麼你可以使用以下來處理普通紅寶石(沒有任何導軌)的起伏:

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