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 which database to connect to.
How do I dynamically and programatically connect ActiveRecord to the right db?
A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.
You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.
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)
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" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With