I want my Entry model to use multiple databases. When a customer joins the network a new database is automaticly created for this customer. Other models will use same database. Is this possible in rails?
-
Did you google your question? This has been asked a hundred times. – Wukerplank Jun 10 '11 at 11:08
-
http://www.google.com/search?q=multiple+database+connection+in+rails&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a – Mohit Jain Jun 10 '11 at 15:33
-
I would really recommend against attempting this. You'd need to establish a database connection for each customer, which will not scale well at all. Is there a reason you can't store all your customers data in the same DB? – Wizard of Ogz Jun 10 '11 at 17:16
-
Here is api doc for connecting multiple databases at the same time. http://apidock.com/rails/ActiveRecord/Base/establish_connection/class – Mukesh Singh Rathaur Apr 30 '13 at 07:05
2 Answers
Funny, I just came up with a solution to this ten minutes ago...
Here goes...
First off define the separate database connection in your database.yml
mine has
production:
adapter: mysql
-etc etc-
Then I added an additional one (for me, I've a legacy database I want to connect to...)
legacy_production:
adapter: mysql
-etc etc-
Repeat this for different environments where appropriate
The next thing I did was create a new file in 'lib' called 'legacy_model.rb' and it looks quite simply like this
require 'active_record'
class LegacyModel < ActiveRecord::Base
self.abstract_class = true
establish_connection "legacy_#{RAILS_ENV}"
end
Now, to make use of this, I just create a class/model and inherit from LegacyModel like so...
class User < LegacyModel
-any validations etc you might want-
end
And voila, it'll access the legacy database instead of the one I'm using.
There are probably better solutions, but this seems to work for me - hope it helps!

- 878
- 7
- 16
-
Oh botheration, I've *just* noticed you wanted the same model accessing multiple databases and my answer doesn't really do that! BAH! Hopefully it'll give you some sort of starting point though. – Lee Jun 10 '11 at 11:20
Is there are particular architectural reason you need to use separate databases? I'd imagine a much more common solution to 'multihoming' applications like this is to store an account_id on your Entry model and have a single database.

- 37,398
- 8
- 88
- 97