简体   繁体   中英

How can I load ActiveRecord database tasks on a Ruby project outside Rails?

ActiveRecord 3.2.14

I want to use ActiveRecord in a non-Rails Ruby project. I want to have available the rake tasks that are defined by ActiveRecord. How can I do that?

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

The above list is the list of tasks that I want to be able to use on my non-Rails Ruby project that uses ActiveRecord. What do I have to write in my Rakefile?

Thanks in advance

The easiest thing to do is to load the tasks already defined in databases.rake. Here is a GIST of how it was done.

Inspired by this GIST by Drogus

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'

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

For Rails 3.x:

You need to manually create the tasks. As example here is how to add them (this example uses the environment variables like Rails):

  namespace :db do
    desc "Drop and create the current database"
    task :recreate => :environment do
      abcs = ActiveRecord::Base.configurations
      ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
      ActiveRecord::Base.connection.recreate_database(ActiveRecord::Base.connection.current_database)
    end
  end

and you'll have the task rake db:recreate available

For Rails 4.x:

If you want to have the ActiveRecord rake tasks available in your ruby app, take a look at the documentation .

Example usage of DatabaseTasks outside Rails could look as such:

include ActiveRecord::Tasks
DatabaseTasks.database_configuration = YAML.load(File.read('my_database_config.yml'))
DatabaseTasks.db_dir = 'db'
# other settings...

DatabaseTasks.create_current('production')

Also you have here an example on how to use ActiveRecord in your ruby aplication.

Create your own! Reference the Rails one though:

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/railties/databases.rake

  1. Create a Rake Task file. To use Rake, generally you want a tasks folder filled with Rake task files. These files have the ".task" extension.
  2. Study the file to link given.
  3. Take parts of that file, or even the entire contents of the file, and add it to your new Rake task file.
  4. Make sure your Rakefile loads those task files. Your Rakefile should have something like this

-

Dir[File.join(PROJECT_ROOT,  'tasks', '**', '*.rake')].each do |file|
  load file
end

I believe you can use the sinatra-activerecord gem even if you're not using Sinatra. I just solved this problem by requiring that gem and then adding

require 'sinatra/activerecord/rake'

to my rakefile .

Once I added that require line the db tasks showed up in my rake -T !

If you are using Sinatra, you can use this gem:

https://github.com/janko-m/sinatra-activerecord

However, if you don't use it either, the source code inside provides a good example on how to implement AR rake tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM