简体   繁体   English

Rails:从外部数据库获取数据

[英]Rails: getting data from an external database

I am trying to read some data from an external database and display it into my home page. 我正在尝试从外部数据库读取一些数据并将其显示在我的主页中。 Here's how far I've gotten: 这是我走了多远:

In my database.yml file: 在我的database.yml文件中:

external_db:
  adapter:  mysql2
  database: external_src
  username: external_src
  password: mypassword
  host: myblog.com

I did not have a pages model, so I created one: /app/models/pages.rb 我没有页面模型,因此创建了一个:/app/models/pages.rb

and added the following to it: 并添加以下内容:

class Blog < ActiveRecord::Base
  establish_connection(:external_db)
  set_table_name :posts
end

Now, in my pages controller, how do I retrieve data? 现在,在页面控制器中,如何检索数据? Let's say I have a table in that database called pots and I would like to retrieve the post with the id 2? 假设我在该数据库中有一个名为pots的表,我想检索ID为2的帖子?

Like any other model so using #find method, ie: 像任何其他模型一样,使用#find方法,即:

Blog.find(2)

Should work 应该管用

Untested 未经测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM