做一个一次性查询到不同的数据库和表 [英] Make a one-off query to a different database and table

查看:128
本文介绍了做一个一次性查询到不同的数据库和表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个词preSS博客(AT /博客完全分开)sellotaped一个侧面的滑轨应用程序。

I have a rails app with a wordpress blog sellotaped on the side (totally separately at /blog).

客户想的要在铁轨上的应用程序的主网页的最新博客文章,所以我需要做一个一次性的MySQL查询到字处理preSS数据库。我怎么会去在Rails应用程序这样做。该字处理preSS距离铁轨完全sperate在数据库方面。

The client want's to the latest blog post on the main homepage of the rails app, so I need to do a one-off mysql query to the word-press database. How would I go about doing this in the rails app. The word-press is completely sperate from rails in terms of database.

干杯。

推荐答案

假设它是访问使用相同的数据库凭据和相同的MySQL服务器上,最简单的方法是将运行一个查询指定的数据库和表从查询条款,因为这样:

Assuming it is accessible using the same database credentials and on the same MySQL server, the easiest way would be to run a query specifying the database and table in the FROM clause of the query, as such:

ActiveRecord::Base.connection.select_one(
    "SELECT * FROM blog_database.posts ORDER BY created_at DESC LIMIT 1")

select_one 将返回列的哈希值。有关方法的详细信息可以在连接物体上使用,请参阅<一href="http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html">this文档。

select_one will return a hash of columns to values. For more information on methods you can use on the connection object, see this documentation.

第二个选项是创建的ActiveRecord的子类,并调用 establish_connection

The second option is to create a subclass of ActiveRecord and call establish_connection:

class Blog < ActiveRecord::Base
  establish_connection :blog

  def self.most_recent_post
    connection.select_one("SELECT * FROM posts ...")
  end
end

您还需要在你的的database.yml 文件中的博客数据库条目。请参阅<一href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-establish_connection">establish_connection有关详细信息,但不幸的是使用它以这种方式真的只有通过查看源$ C ​​$下 establish_connection 众所周知的。

You will also need to make a blog database entry in your database.yml file. See establish_connection for more details, although unfortunately using it in this way is really only known by looking at the source code for establish_connection.

然后就可以使用查询博客数据库连接,如下所示:

Then you can use the blog database connection in queries, like so:

Blog.connection.select_one("SELECT * FROM posts ...")

什么是好的,这样做是这样,现在是你有一个很好的地方定义一个方法(在博客类,作为一个类的方法)来获取数据,我已经在上面做了。

What is nice about doing it this way is now you have a nice place to define a method (in the Blog class, as a class method) to fetch the data, as I have done above.

这两种策略,应该可以正常使用Rails x或3 x。

Both these strategies should work fine with Rails 2.x or 3.x.

这篇关于做一个一次性查询到不同的数据库和表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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