ruby 使用database.yml Rails多租户/多数据库和子域

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 使用database.yml Rails多租户/多数据库和子域相关的知识,希望对你有一定的参考价值。

after "deploy:migrate", "deploy:migrate_subdomains"
  task :migrate_subdomains do
    configs = YAML::load(File.open(File.expand_path("../../../config/database.yml", __FILE__)))
    configs["subdomains"].each do |subdomain|
      begin
        run "cd #{current_path} && #{rake} db:migrate RAILS_ENV=#{subdomain}"
      rescue Exception => e
        Capistrano::CLI.ui.say "*** [err] #{e.message}"
      end
    end
  end
common: &common
  adapter: postgresql
  username: username
  password: password
  host: localhost
  encode: utf8

# Subdomains
subdomains: ["sub1", "sub2", "sub3"]

sub1:
  <<: *common  
  database: sub1
sub2:
  <<: *common
  database: sub2
sub3:
  <<: *common
  database: sub3
  before_filter :select_database

  def select_database
    if Rails.env == "production"
      unless request.subdomain.empty?
        begin
          subdomain = request.subdomains.first
          config    = ActiveRecord::Base.configurations[subdomain]
          if config
            ActiveRecord::Base.establish_connection(config)
          else
            ActiveRecord::Base.establish_connection(Rails.env)
            flash[:error] = "Database not found"
          end
        rescue
          render :text => "Invalid subdomain"
        end
      end
    end
  end

以上是关于ruby 使用database.yml Rails多租户/多数据库和子域的主要内容,如果未能解决你的问题,请参考以下文章

Ruby on Rails database.yml 中的套接字声明是啥?

为 Ruby on Rails Database.yml 文件正确配置 MySQL

fe_sendauth:Ruby没有提供密码(PG :: ConnectionBad),但在Rails中没问题

Docker + Rails + MySQL =忽略database.yml中的环境变量

在 Rails 项目中忽略 .gitignore config/database.yml

如何在 database.yml 文件中设置 rails 环境变量?