1

I am building a Rails 4 app and trying to have separate databases for different models.

For example;
- the Users model will connect to a database at 192.168.1.2
- the Cars model will connect to a database at 192.168.1.3
- the Books model will connect to a database at 192.168.1.4

How can I achieve this? I've been looking all over the place but haven't found exactly what I want... https://devcenter.heroku.com/articles/concurrency-and-database-connections

The DBCharmer Plugin seems to do it with 'switch_connection_to' BUT it seems it switches the whole database connection every time and does not make use of persistent connections...
--> They mention 'establish_connection' but I have not been able to figure out how to use this /:

Thanks for the help!

FYI: This is using Mysql btw but I assume the solution for Sqlite or postgreSQL would work in the same way.


EDIT

I tested 'establish_connection' in my models and this works great. BUT I was hoping there would be a better way since the db migrations don't get routed to the correct database when doing 'rake db:migrate'

Right?

So if this is correct, then I am supposed to manually export DB schema into the other DB?

2 Answers 2

1

you can define more database connections than development, production and test in your database.yml, e.g. in addition to that: users_db_development:

users_db_development:
  host: 192.168.1.2
  ...

then in your model (class) you do:

class User < ActiveRecord::Base
  establish_connection "users_db_#{Rails.env}"
end

this works at least in Rails 3, should work in 4 as well.

Sign up to request clarification or add additional context in comments.

2 Comments

but please don't expect has_many etc between different databases to work
Thanks! I had actually tested this but was wondering if there was a way to also have the DB migrations work with multiple databases... in this case.. the migration only affects the first database in databases.yml ): See my edit
0

I'd also love to learn about this

You need to look at something called MultiTenancy - Wikipedia

1 Comment

nice man, yea MultiTenancy is actually also a part of this Saas platform... I'm no rails expert but I'm sure there is a well known way to do this as Saas and Paas is kinda the hot trend these days, and Rails is too (:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.