Assuming it is accessible using the same database credentials and on the same MySQL server, the easiest way would be to run a query defining the database and table in the FROM query, as such:
ActiveRecord::Base.connection.select_one( "SELECT * FROM blog_database.posts ORDER BY created_at DESC LIMIT 1")
select_one will return the hash of the columns in the values. For more information about the methods you can use in the connection object, see this documentation .
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
You will also need to record the blog database in the database.yml file. See establish_connection for more details, although, unfortunately, using this method is really only known when viewing the establish_connection source code.
Then you can use the blog database connection in the queries, for example:
Blog.connection.select_one("SELECT * FROM posts ...")
What you like to do it this way, now you have a good place to define a method (in the Blog class, as a class method) to retrieve the data, as I said above.
Both of these strategies should work fine with Rails 2.x or 3.x.
wuputah
source share