gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:37:28 24 4
gpt4 key购买 nike

事件记录 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

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

提前致谢

最佳答案

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

灵感来自 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'

关于ruby - 如何在 Rails 之外的 Ruby 项目上加载 ActiveRecord 数据库任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19206764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com