2012-08-09 4 views
7

레일 외부에서 ActiveRecord를 사용하고 있습니다. 나는 마이그레이션의 뼈대를 생성하는 프로그램 (뿐만 아니라 시스템을 수집하고 유지 관리하는 시스템)을 원할 것이다.레일 외부에서 마이그레이션 생성

누구든지 제안 할 수 있습니까?

답변

3

비 Rails 프로젝트에서 Rails 데이터베이스 마이그레이션을 사용할 수있는 보석이 있습니다. 그 이름은 "standalone_migrations"여기

가 링크

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

+3

이 링크 질문에 대답 할 수 있습니다. 대답의 핵심 부분을 여기에 포함시키고 참조 용 링크를 제공하는 것이 좋습니다. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. –

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 
관련 문제