简体   繁体   English

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

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

ActiveRecord 3.2.14 ActiveRecord 3.2.14

I want to use ActiveRecord in a non-Rails Ruby project. 我想在非Rails Ruby项目中使用ActiveRecord。 I want to have available the rake tasks that are defined by ActiveRecord. 我希望可以使用ActiveRecord定义的rake任务。 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. 上面的列表是我希望能够在使用ActiveRecord的非Rails Ruby项目上使用的任务列表。 What do I have to write in my Rakefile? 我在Rakefile中要写什么?

Thanks in advance 提前致谢

The easiest thing to do is to load the tasks already defined in databases.rake. 最简单的方法是加载已在databases.rake中定义的任务。 Here is a GIST of how it was done. 这是一个如何完成它的GIST。

Inspired by this GIST by Drogus 灵感来自Drogus的GIST

Rakefile.rb 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: 对于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): 这里的例子是如何添加它们(这个例子使用像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 你将拥有任务rake db:recreate available

For Rails 4.x: 对于Rails 4.x:

If you want to have the ActiveRecord rake tasks available in your ruby app, take a look at the documentation . 如果您想在ruby应用程序中使用ActiveRecord rake任务,请查看文档

Example usage of DatabaseTasks outside Rails could look as such: 在Rails之外使用DatabaseTasks的示例可能如下所示:

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. 你也需要在这里对如何在Ruby aplication使用ActiveRecord的例子。

Create your own! 创建你自己的! Reference the Rails one though: 尽管参考了Rails:

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

  1. Create a Rake Task file. 创建一个Rake任务文件。 To use Rake, generally you want a tasks folder filled with Rake task files. 要使用Rake,通常需要一个填充了Rake任务文件的任务文件夹。 These files have the ".task" extension. 这些文件具有“.task”扩展名。
  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. 获取该文件的一部分,甚至文件的全部内容,并将其添加到新的Rake任务文件中。
  4. Make sure your Rakefile loads those task files. 确保您的Rakefile加载这些任务文件。 Your Rakefile should have something like this 你的Rakefile应该有这样的东西

- -

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. 即使你没有使用Sinatra,我相信你也可以使用sinatra-activerecord gem。 I just solved this problem by requiring that gem and then adding 我刚刚通过要求宝石然后添加来解决这个问题

require 'sinatra/activerecord/rake'

to my rakefile . 到我的rakefile

Once I added that require line the db tasks showed up in my rake -T ! 一旦我添加了require行, db任务出现在我的rake -T

If you are using Sinatra, you can use this gem: 如果您使用的是Sinatra,则可以使用此gem:

https://github.com/janko-m/sinatra-activerecord 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. 但是,如果您不使用它,则内部源代码提供了有关如何实现AR rake任务的良好示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Rails外的ruby脚本中使用ActiveRecord? - How to use ActiveRecord in a ruby script outside Rails? Ruby on Rails:如何执行存储在数据库中的activerecord查询? - Ruby on Rails: how can we execute activerecord query stored in database? 如何使用rails 3显示路径在Ruby on Rails项目目录之外的图像? - How can I display an image whose path is outside my Ruby on Rails project directory using rails 3? 在Rails之外使用ActiveRecord :: Database :: Tasks时,我需要配置什么以避免开发数据库未配置错误? - When using ActiveRecord::Database::Tasks outside of Rails, what do I need to configure to avoid a development database not configured error? 如何在Ruby脚本的Rails中使用现有的ActiveRecord模型 - How can I use existing Activerecord model in rails in ruby script 如何将ActiveRecord Create用于Ruby on Rails的多个记录? - how can I use ActiveRecord Create for multiple records Ruby on Rails? 如何显示路径在Ruby on Rails项目目录之外的图像 - How can I display an image whose path is outside my Ruby on Rails project directory 如何使用activerecord将数据加载到数据库中 - How can I load data into database using activerecord Ruby on Rails:如何在Rails项目中添加CSS文件? - Ruby on Rails: How can I add a css file with rails project? 如何在同一个 Ruby Rails 项目中配置 MongoMapper 和 ActiveRecord - How to configure MongoMapper and ActiveRecord in same Ruby Rails Project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM