最近工作需要从A数据库迁移部分数据至B数据库,中间需要同时连接A,B两个数据库,故做了相关调研。从本质上来讲,ActiveRecord连接数据库是由ActiveRecord::Base的establish_connection方法来处理的,只要用不同的数据库配置来调用这个方法,就可以实现连接不同的数据库了。具体操作过程很简单:
1.在config/database.yml中设置多个数据库配置:
database_a:
adapter: mysql2
host: x.x.x.x
username: xxx
password: xxx
database: xxx
database_b:
adapter: mysql2
host: x.x.x.x
username: xxx
password: xxx
database: xxx
2.在Model中新增对应model:
class MyModel < ActiveRecord::Base
self.abstract_class = true
establish_connection :database_b
end
其中self.abstract_class = true的作用是:
# Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
# If you are using inheritance with ActiveRecord and don't want child classes
# to utilize the implied STI table name of the parent class, this will need to be true.
# For example, given the following:
#
# class SuperClass < ActiveRecord::Base
# self.abstract_class = true
# end
# class Child < SuperClass
# self.table_name = 'the_table_i_really_want'
# end
#
#
# <tt>self.abstract_class = true</tt> is required to make <tt>Child<.find,.create, or any Arel method></tt> use <tt>the_table_i_really_want</tt> instead of a table called <tt>super_classes</tt>
3.在controller中调用:require 'my_model'
即可正常使用了。
原文:http://qa.blog.163.com/blog/static/190147002201451310551844/