Reputation: 25
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?
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
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