Rails引擎具有多个数据库

时间:2016-09-29 08:48:56

标签: mysql ruby-on-rails rails-engines

我在Ruby on Rails中创建应用程序,它有许多引擎(用于模块化)。

我想为每个引擎提供不同的数据库。如何配置?

数据库 - MYSQL

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

一般方法是查看框架源并决定是否可以重用。

我们首先来看一下activerecord/lib/active_record/railties/databases.rake(v5.0.7)。例如db:create的实现方式。

我们将看到ActiveRecord::Tasks::DatabaseTasks.create_current

打开ActiveRecord::Tasks::DatabaseTasks,看看

    # The possible config values are:
    #
    # * +env+: current environment (like Rails.env).
    # * +database_configuration+: configuration of your databases (as in +config/database.yml+).
    # * +db_dir+: your +db+ directory.
    # * +fixtures_path+: a path to fixtures directory.
    # * +migrations_paths+: a list of paths to directories with migrations.
    # * +seed_loader+: an object which will load seeds, it needs to respond to the +load_seed+ method.
    # * +root+: a path to the root of the application.
    #
    # Example usage of DatabaseTasks outside Rails could look as such:
    #
    #   include ActiveRecord::Tasks
    #   DatabaseTasks.database_configuration = YAML.load_file('my_database_config.yml')
    #   DatabaseTasks.db_dir = 'db'
    #   # other settings...

这样,我们将获得以下解决方案:

namespace :your_engine do
  namespace :db do

    task :load_config do
      ActiveRecord::Tasks::DatabaseTasks.database_configuration = YAML.load_file("config/database_your_engine.yml")
      ActiveRecord::Tasks::DatabaseTasks.db_dir = "db_your_engine"
      ActiveRecord::Tasks::DatabaseTasks.migrations_paths = [ "components/your_engine/db/migrate" ]

      ActiveRecord::Base.configurations = ActiveRecord::Tasks::DatabaseTasks.database_configuration
      ActiveRecord::Migrator.migrations_paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths

      # You can observe following values to see how settings applied.
      # puts ActiveRecord::Base.configurations
      # puts ActiveRecord::Migrator.migrations_paths
      # puts ActiveRecord::Tasks::DatabaseTasks.database_configuration
      # puts ActiveRecord::Tasks::DatabaseTasks.migrations_paths
    end

    desc "Create Your DB"
    task create: :load_config do
      ActiveRecord::Tasks::DatabaseTasks.create_current
    end
  end
end

用于删除/迁移和其他所需任务的相同方法。

这是一个很好的一般规则-知道您的堆叠至少比使用的堆叠低一层。有时阅读基础资料比直接回答更有帮助。

我将在继续解决方案的同时更新此答案...