每个模型一个以上的数据库 [英] more than one database per model
本文介绍了每个模型一个以上的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Service < ActiveRecord::Base
establish_connection(
:adapter => "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
我怎样才能做到这一点?
How can i achieve this?
数据库名称是动态的.我希望服务模型动态连接数据库.当我输入 Service.use(weeweweaszxc).all
时,它必须使用 weweweaszxc 数据库.
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.
推荐答案
试试看这里的这个问题.如何使用 ActiveRecord 最好地处理每个模型的数据库连接?
Try taking a look as this question over here. How to best handle per-Model database connections with ActiveRecord?
他们像往常一样在 database.yml 文件中定义数据库,并在模型中调用它:
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
使用的信息来自 Priit 的回答
这篇关于每个模型一个以上的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文