13

我想要规范的方式来做到这一点。我的 Google 搜索不足。我有一个 ActiveRecord 模型,它应该映射到与应用程序的其余部分不同的数据库。我也想将新配置存储在 database.yml 文件中。

我知道应该调用建立连接,但不清楚在哪里。这是我到目前为止得到的,但它不起作用:

class Foo < ActiveRecord::Base
    establish_connection(('foo_' + ENV['RAILS_ENV']).intern)
end
4

2 回答 2

21

此外,最好对使用不同数据库的模型进行子类化,例如:

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

在你的模型中

class Foo < AnotherBase
end

当您需要添加访问相同的另一个数据库的后续模型时,它很有用。

于 2008-09-27T10:06:55.643 回答
5

呵呵。我是正确的!更干净:

class Foo < ActiveRecord::Base
    establish_connection "foo_#{ENV['RAILS_ENV']}"
end

pragedave.pragprog.com 上的好帖子。

于 2008-09-26T19:05:01.990 回答