Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 833
Alve Avatar asked Jan 17 '12 13:01

Alve


People also ask

Can we create a table without a model in Rails?

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.

What three databases are referred to by a Rails application?

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.


1 Answers

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

like image 199
Arun Kumar Arjunan Avatar answered Oct 20 '22 22:10

Arun Kumar Arjunan