Make a one-time request to another database and table

I have a rails application with a wordpress block sold on the side (completely separately in the / blog).

The client wants to get the latest blog post on the rails application main page, so I need to make a one-time mysql request to the word-press database. How do I do this in a rails application. The word press is completely off track in terms of the database.

Greetings.

+6
mysql ruby-on-rails activerecord wordpress
source share
1 answer

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.

+9
source share

All Articles