Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 300
Tilendor Avatar asked Oct 07 '08 20:10

Tilendor


People also ask

What does Rails DB Migrate do?

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.

Which command is true to rollback migration in Rails?

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.


2 Answers

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) 
like image 109
Jim Puls Avatar answered Sep 25 '22 10:09

Jim Puls


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" }) 
like image 26
Tilendor Avatar answered Sep 26 '22 10:09

Tilendor