How can I query a MySQL database from a Rails application without models?

How can I execute a SQL query from a Rails application to a MySQL database?

My application uses Postgres as the primary database, but I need to read some information from the secondary MySQL database. I cannot create models because the MySQL database contains more than 100 tables, named incompatibly for each table. Can this be done without ActiveRecord or in any other way?

+7
source share
1 answer

You can directly use mysql2 gem. Read the documentation here: https://github.com/brianmario/mysql2

Or:

You can create a new class such as 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 save configuration data in a database.yml file: http://weare.buildingsky.net/2006/12/06/multiple-concurrent-database-connections-with-activerecord

+13
source

All Articles