glesage
glesage

Reputation: 975

Rails 4 Database for each model

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?

Upvotes: 1

Views: 309

Answers (2)

Marian Theisen
Marian Theisen

Reputation: 6353

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.

Upvotes: 1

Richard Peck
Richard Peck

Reputation: 76784

I'd also love to learn about this

You need to look at something called MultiTenancy - Wikipedia

Upvotes: 0

Related Questions