Friday, February 11, 2011

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?

  • 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" })
    
    From Tilendor
  • 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(RAILS_ENV)
    
    From Jim Puls

0 comments:

Post a Comment