如何使rails外部数据库调用? [英] how to make rails external database calls?

查看:244
本文介绍了如何使rails外部数据库调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想能够添加一个外部数据库到我的 config / database.yml 然后从它建模一个表。

So i'd like to be able to add an external database to my config/database.yml Then model one table from it.

这是可能吗?

连接到不同模型中的多个数据库

"Connection to multiple databases in different models

连接通常通过 ActiveRecord :: Base.establish_connection 创建,并由 ActiveRecord :: Base.connection 检索。 ActiveRecord :: Base 会使用这个连接,但你也可以设置一个特定类的连接,例如 Course ActiveRecord :: Base ,但驻留在不同的数据库中,您只需说 Course.establish_connection code> Course ,所有的子类都将使用这个连接。

Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say Course.establish_connection and Course and all of its subclasses will use this connection instead.

code> ActiveRecord :: Base 这是一个由类索引的Hash如果请求连接,则retrieve_connection方法将向上爬到类层次结构,直到在连接池中找到连接。

This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool. "

推荐答案

首先,在database.yml中定义连接信息:

First, define the connection information in database.yml:

my_external_db:
  adapter: mysql
  username: ...
  ....

然后,创建模型并将其连接到外部db

Then, create the model and connect it to the external db

class MyExternalModel < ActiveRecord::Base
  establish_connection(:my_external_db)
  set_table_name 'my_external_table'
end

这篇关于如何使rails外部数据库调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆