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

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

提交回复
热议问题