ActiveRecord::Base.establish_connection(:another_db) 不工作
ActiveRecord::Base.establish_connection(:another_db) is not working
database.yml定义了两个数据库,production
(默认)和slave
。
使用控制台执行ActiveRecord::Base.establish_connection(:slave)
然后User.count
,查询仍然在production
上执行。
为什么会发生这种情况以及如何在 slave
上对 运行 进行查询?
在用户上添加一个方法来切换连接
class User < ActiveRecord::Base
def self.connect_to_slave
establish_connection :slave
end
def self.connect_to_prod
establish_connection :production
end
end
database.yml定义了两个数据库,production
(默认)和slave
。
使用控制台执行ActiveRecord::Base.establish_connection(:slave)
然后User.count
,查询仍然在production
上执行。
为什么会发生这种情况以及如何在 slave
上对 运行 进行查询?
在用户上添加一个方法来切换连接
class User < ActiveRecord::Base
def self.connect_to_slave
establish_connection :slave
end
def self.connect_to_prod
establish_connection :production
end
end