开发者

connect rails application to many databases

lets say I have users, and each user belongs to some group. For security reasons I want to have separate database for each group. I imagine that objects U开发者_如何学编程ser and Group are stored in one central database, and authentication is performed against this database, but all other objects connects dynamically to different database which is defined in Group object.

So question is: how do I connect dynamically to different database with my object depending on some parameters (ex. dbname)?


you can use class method "establish_connection", but to be honest, I don't know if this can be called dynamically every time you need. I use it for models which connects to different database this way:

class SomeModel < ActiveRecord::Base
  establish_connection "second_#{Rails.env}"
end

database.yml:

development:
  adapter: mysql2
  username: web
  password:
  database: first_db
  pool: 5

second_development:
  ...
  database: second_db
  pool: 5

As far as I know, establish connection can be also called right with Hash containing the parameteres from database.yml, e.g.

establish_connection { :username => "web", :database => "..." }

But I don't know if this will be using connection pooling if you do it this way.

I also use it like that when I write script outside rails (just pure ruby with inclusion of the activerecord) and then I connect to db manually.

I hope this helps.

Regards, NoICE


Use MultiConfig gem I created to make this easy.

You could specify the configs in separate file like second.yml etc and then call:

ActiveRecord::Base.config_file = 'second' # for all models

or

SomeModel < ActiveRecord::Base
    self.config_file = 'second'
end

This way it will be much easier to maintain and cleaner looking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜