Reputation: 1465
How can I execute a SQL query from a Rails application to a MySQL database?
My application uses Postgres as a primary database, but I need to read some information from a secondary MySQL database. I can't create models because the MySQL database has more than 100 tables, named in an incompatible way for every table. Can it be done without ActiveRecord or some other way?
Upvotes: 8
Views: 3634
Reputation: 6857
You can use mysql2 gem directly. Read the documentation here: https://github.com/brianmario/mysql2
Or:
You can create a new class like MysqlConnection like this:
class MysqlConnection < ActiveRecord::Base
self.establish_connection(:adapter => 'mysql', :database => 'some-database-name') # Set all the other required params like host, user-name, etc
end
From now on, you can do,
MysqlConnection.connection.select_all("SELECT * FROM table_name")
Follow the link to understand how to store the configuration details in database.yml: http://weare.buildingsky.net/2006/12/06/multiple-concurrent-database-connections-with-activerecord
Upvotes: 13