开发者

more than one database per model

开发者 https://www.devze.com 2023-03-12 14:17 出处:网络
class Service < ActiveRecord::Base establish_connection( :adapter=> \"mysql\", :host=> \"myip\",
class Service < ActiveRecord::Base

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

end

This wor开发者_高级运维ks

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.


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

0

精彩评论

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