rubyruby
rubyruby

Reputation: 25

more than one database per model

class Service < ActiveRecord::Base

establish_connection(
  :adapter  => "mysql",
  :host     => "myip",
  :username => "myusername",
  :password => "mypassword",
  :database => "mydatabase"
)

end

This works

Service.all #connects to mydatabase

But i need something like that.

Service.use(mydatabase1).all #connects to mydatabase1
Service.use(mydatabase2).all #connects to mydatabase2

How can i achieve this?

Update

Database names are dynamic. I want Service model to connect database dynamically. When i type Service.use(weeweweaszxc).all it has to use weeweweaszxc database.

Upvotes: 2

Views: 532

Answers (1)

Devin M
Devin M

Reputation: 9752

Try taking a look as this question over here. How to best handle per-Model database connections with ActiveRecord?

They define the databases in the database.yml file like normal and call this in the model:

class AnotherDatabase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "anotherbase_#{RAILS_ENV}"
end

Used info from Priit's answer

Upvotes: 4

Related Questions