Reputation: 3779
[Disclaimer: I'm wearing my devops hat, which isn't even my full-time hat. I don't have a RoR hat, I just do my best.]
I have a RoR application that runs in several data centres. MySQL lets me replicate my data to all the DC's, but only one instance of MySQL is writeable. (Yes, there are techniques to replicate back to the master, but I don't believe RoR maintains the necessary contracts to do that safely. Maybe I'm wrong.)
Most of the time, RoR is reading from MySQL, so it would be much faster if I could tell RoR to use the local MySQL instance except when it needs to write something.
Or maybe I'm looking at the problem incorrectly and I can tell MySQL that this is what I mean. (Indeed, perhaps the right thing to do is to set up a MySQL Proxy instance as well and tell it to do read/write splitting.)
Upvotes: 2
Views: 155
Reputation: 4451
One solution is to create two different connections for the same class, one connection will connect to your writeable db, and the other your readable db.
Keep your original db connection class, but then create another readable-only class, so you'll have two different classes defined:
class Example < ActiveRecord::Base
end
class ReadExample < ActiveRecord::Base
establish_connection configurations['read_example'][Rails.env]
end
Wherever you want to make read-only call, replace 'Example' with 'ReadExample'.
I haven't tested this, but I think it should work. The only danger is putting 'Readable' class on a call that actually writes.
Upvotes: 0