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?
There is no harm in creating a Model for a table in Rails. Though, if you wish to avoid it, you can use raw SQL queries for same. Save this answer.
Ruby on Rails recommends to create three databases - a database each for development, testing, and production environment. According to convention, their names should be − library_development. library_production. library_test.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With