如何最好地处理与ActiveRecord的每个模型数据库连接?
-
02-07-2019 - |
题
我希望以规范的方式来做到这一点。我的谷歌搜索已经缩短了。我有一个ActiveRecord模型应该映射到不同于应用程序其余部分的数据库。我想将新配置存储在database.yml文件中。
我知道应该调用establish_connection,但不清楚在哪里。这是我到目前为止所得到的,它不起作用:
class Foo < ActiveRecord::Base
establish_connection(('foo_' + ENV['RAILS_ENV']).intern)
end
解决方案
此外,最好将使用不同数据库的模型子类化,例如:
class AnotherBase < ActiveRecord::Base
self.abstract_class = true
establish_connection "anotherbase_#{RAILS_ENV}"
end
在你的模特中
class Foo < AnotherBase
end
当您需要添加访问相同的另一个数据库的后续模型时,它非常有用。
其他提示
嘿。我是正确的!更干净:
class Foo < ActiveRecord::Base
establish_connection "foo_#{ENV['RAILS_ENV']}"
end
不隶属于 StackOverflow