每个模型不止一个数据库

class Service  "mysql", :host => "myip", :username => "myusername", :password => "mypassword", :database => "mydatabase" ) end 

这很有效

 Service.all #connects to mydatabase 

但我需要这样的东西。

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

我怎样才能做到这一点?

更新

数据库名称是动态的。 我希望Service模型动态连接数据库。 当我键入Service.use(weeweweaszxc).all它必须使用weeweweaszxc数据库。

试着看看这个问题。 如何最好地处理与ActiveRecord的每个模型数据库连接?

他们像正常一样在database.yml文件中定义数据库,并在模型中调用它:

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

来自Priit答案的使用信息