NooB8374 NooB8374 - 1 month ago 6
Ruby Question

Connecting to two different database in ruby at runtime

I have a database being hosted in development environment and production environment. I am writing a api which based on a parameter in request will write to table in either environment or production db. I have put both entries in by database.yaml file :


development:

adapter: mysql2

database: db1

username: root

password:

timeout: 5000

host: a.b.c.d

pool: 5

port: 1234

production:
adapter: mysql2
database: db1
username: root

password:

timeout: 5000

host: a.b.c.e

pool: 5

port: 1234


This is my active record :

class table1 < ActiveRecord::Base
self.table_name = 'table1'
end


How do i write to different environments based on a request parameter ?

Answer

You could use two models for the same table, one connected to the production database and the other connected to the development database.

Lets say your connection parameters are in the variables $production and $developent.

You would also have to adapt your code to know which model to use.

class table1 < ActiveRecord::Base  
 establish_connection($production)
 self.table_name = 'table1' 
end

class table1test < ActiveRecord::Base  
 establish_connection($developent)
 self.table_name = 'table1' 
end
Comments