1.增加 external_database.yml 在 project/config,配置如下 (以连接 postgresql 为例):
development:
adapter: postgresql
database: DataBase_DEV
encoding: utf8
pool: 15
timeout: 5000
username: yourname
password: yourpassword
host: localhost
production:
adapter: postgresql
database: DataBase_PROD
encoding: utf8
pool: 15
timeout: 5000
username: yourname
password: yourpassword
host: remote ip address
2.增加 external_databases.rb 文件在 project/config/initializers,内容如下 (初始化外部数据库的各个参数):
EXTERNAL_DATABASE = YAML.load_file("#{Rails.root}/config/external_database.yml")[Rails.env]
3.增加 external_db_object.rb 文件在 projrct/app/models/,内容如下(建立外部数据库连接):
class ExternalDbObject < ActiveRecord::Base
self.abstract_class = true
begin
if %w[production development test].include? Rails.env
establish_connection(
:adapter => EXTERNAL_DATABASE ["adapter"],
:pool => EXTERNAL_DATABASE ["pool"],
:timeout => EXTERNAL_DATABASE ["timeout"],
:host => EXTERNAL_DATABASE ["host"],
:database => EXTERNAL_DATABASE ["database"],
:username => EXTERNAL_DATABASE ["username"],
:password => EXTERNAL_DATABASE ["password"],
:encoding => EXTERNAL_DATABASE ["encoding"])
end
rescue Exception => e
Rails.logger.error("Failed to connect to #{EXTERNAL_DATABASE ["adapter"]}")
Rails.logger.error(e.message)
Rails.logger.error(e.backtrace.join("\n"))
end
end
4.此上三部已设置好外部数据库的连接信息,此时如果要用外部数据库的某个表(例如 sample_cars)建立 model:
class Car < ExternalDbObject (注意此时要继承ExternalDbObject 而不是ActiveRecord::Base)
self.table_name = "sample_cars"
end
至此完成了外部数据库的连接,指定了 sample_cars 表作为 Car model 对应的表,此时表中各个字段均可为此 model 所用,包括 find 各方法; 如果用到多张表(每个都继承 ExternalDbObject),而且表间有关联,只需要添加关联,association 关系完全适用