如何在Rails外部的Ruby项目上加载ActiveRecord数据库任务?

p.m*_*los 14 ruby rake activerecord

ActiveRecord 3.2.14

我想在非Rails Ruby项目中使用ActiveRecord.我希望可以使用ActiveRecord定义的rake任务.我怎样才能做到这一点?

rake db:create           # Create the database from DATABASE_URL or config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)
rake db:drop             # Drops the database using DATABASE_URL or the current Rails.env (use db:drop:all to drop all databases)
rake db:fixtures:load    # Load fixtures into the current environment's database
rake db:migrate          # Migrate the database (options: VERSION=x, VERBOSE=false)
rake db:migrate:status   # Display status of migrations
rake db:rollback         # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:dump      # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load      # Load a schema.rb file into the database
rake db:seed             # Load the seed data from db/seeds.rb
rake db:setup            # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)
rake db:structure:dump   # Dump the database structure to db/structure.sql
rake db:version          # Retrieves the current schema version number
Run Code Online (Sandbox Code Playgroud)

上面的列表是我希望能够在使用ActiveRecord的非Rails Ruby项目上使用的任务列表.我在Rakefile中要写什么?

提前致谢

小智 20

最简单的方法是加载已在databases.rake中定义的任务.这是一个如何完成它的GIST.

灵感来自Drogus的GIST

Rakefile.rb

require 'yaml'
require 'logger'
require 'active_record'

include ActiveRecord::Tasks

class Seeder
  def initialize(seed_file)
    @seed_file = seed_file
  end

  def load_seed
    raise "Seed file '#{@seed_file}' does not exist" unless File.file?(@seed_file)
    load @seed_file
  end
end


root = File.expand_path '..', __FILE__
DatabaseTasks.env = ENV['ENV'] || 'development'
DatabaseTasks.database_configuration = YAML.load(File.read(File.join(root, 'config/database.yml')))
DatabaseTasks.db_dir = File.join root, 'db'
DatabaseTasks.fixtures_path = File.join root, 'test/fixtures'
DatabaseTasks.migrations_paths = [File.join(root, 'db/migrate')]
DatabaseTasks.seed_loader = Seeder.new File.join root, 'db/seeds.rb'
DatabaseTasks.root = root

task :environment do
  ActiveRecord::Base.configurations = DatabaseTasks.database_configuration
  ActiveRecord::Base.establish_connection DatabaseTasks.env.to_sym
end

load 'active_record/railties/databases.rake'
Run Code Online (Sandbox Code Playgroud)


thu*_*der 6

您可以尝试独立迁移gem:https: //github.com/thuss/standalone-migrations

  • 另请参阅[active_record_migrations](https://github.com/rosenfeld/active_record_migrations),根据[本期](https://github.com/thuss/standalone-migrations/issues/88),它支持activerecord 4. (2认同)