Leon
Leon

Reputation: 1302

Connect to 2 databases from same model in Rails

I have an application that run in 2 different countries. Lets say US and Brazil. I have a User Model that connects to US or Brazil depending on a param passed by calling:

User.establish_connection("Brazil_DB") User.establish_connection("US_DB")

The problem I am facing is that if a US user comes in the middle of a session from a Brazil user ActiveRecord Drops my Brazil Connection and connects to the US DB.

Is there any way to manage such situations in ActiveRecord?

Upvotes: 1

Views: 181

Answers (1)

tadman
tadman

Reputation: 211700

You really should have one database with a nationality flag on your relevant tables, or two different applications deployed in different datacentres. This kind of thing will be an enormous hassle.

ActiveRecord can handle having different tables in different databases, but it's not capable of understanding how to handle one table living in several at the same time. You need an extension to manage this.

The problem becomes serious when you do things like:

 Model.find(params[:id])

Which connection should you use for that? Unless you have additional context the answer is "I don't know."

It really sounds like you should deploy two instances of your application each with a different database.yml file.

Upvotes: 1

Related Questions