如何最好地处理每个模型数据库ActiveRecord的连接? [英] How to best handle per-Model database connections with ActiveRecord?
问题描述
我想规范的方式来做到这一点。我的谷歌搜索想出短。我有一个ActiveRecord模型应该映射到不同的数据库应用程序的其余部分的。我想存储在database.yml文件,新的配置也是如此。
据我所知,establish_connection应该叫,但目前还不清楚在哪里。以下是我有这么远了,这是行不通的:
类Foo<的ActiveRecord :: Base的
establish_connection(('foo_'+ ENV ['RAILS_ENV'])。实习生)
结束
此外,它是继承你的模型,使用不同的数据库,如一个好主意:
类AnotherBase<的ActiveRecord :: Base的
self.abstract_class =真
establish_connectionanotherbase _#{} RAILS_ENV
结束
和模型中的
类Foo< AnotherBase
结束
当你需要添加访问同一个,另一个数据库后续机型这是非常有用的。
I'd like the canonical way to do this. My Google searches have come up short. I have one ActiveRecord model that should map to a different database than the rest of the application. I would like to store the new configurations in the database.yml file as well.
I understand that establish_connection should be called, but it's not clear where. Here's what I got so far, and it doesn't work:
class Foo < ActiveRecord::Base
establish_connection(('foo_' + ENV['RAILS_ENV']).intern)
end
Also, it is a good idea to subclass your model that uses different database, such as:
class AnotherBase < ActiveRecord::Base
self.abstract_class = true
establish_connection "anotherbase_#{RAILS_ENV}"
end
And in your model
class Foo < AnotherBase
end
It is useful when you need to add subsequent models that access the same, another database.
这篇关于如何最好地处理每个模型数据库ActiveRecord的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!