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

后端 未结 4 522
耶瑟儿~
耶瑟儿~ 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:06

    It's been a while since this question has been created, but I have to say that there is another way too:

    conn_config = ActiveRecord::Base.connection_config
    conn_config[:database] = new_database
    ActiveRecord::Base.establish_connection conn_config
    
    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2020-12-12 17:13

    You can also do this easily without hardcoding anything and run migrations automatically:

    customer = CustomerModel.find(id)
    spec = CustomerModel.configurations[RAILS_ENV]
    new_spec = spec.clone
    new_spec["database"] = customer.database_name
    ActiveRecord::Base.establish_connection(new_spec)
    ActiveRecord::Migrator.migrate("db/migrate_data/", nil)
    

    I find it useful to re-establish the old connection on a particular model afterwards:

    CustomerModel.establish_connection(spec)
    
    0 讨论(0)
  • 2020-12-12 17:24

    you can change the connection to ActiveRecord at any time by calling ActiveRecord::Base.establish_connection(...)

    IE:

     ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
        :username => "root", :password => "password" })
    
    0 讨论(0)
提交回复
热议问题