How can I dynamically change the Active Record database for all models in Ruby on Rails?

后端 未结 4 540
耶瑟儿~
耶瑟儿~ 2020-12-12 16:42

In our program, each customer gets their own database. We e-mail them a link that connects them to their database. The link contains a GUID that lets the program know whic

4条回答
  •  无人及你
    2020-12-12 17:10

    class Database
      def self.development!
        ActiveRecord::Base.establish_connection(:development)
      end
    
      def self.production!
        ActiveRecord::Base.establish_connection(ENV['PRODUCTION_DATABASE'])
      end
    
      def self.staging!
        ActiveRecord::Base.establish_connection(ENV['STAGING_DATABASE'])
      end
    end
    

    And in .env (with dotenv-rails gem for instance):

    PRODUCTION_DATABASE=postgres://...
    STAGING_DATABASE=postgres://...
    

    And now you can:

    Database.development!
    User.count
    Database.production!
    User.count
    Database.staging!
    User.count
    # etc.
    

提交回复
热议问题