Reputation: 2016
I am trying to establish a connection to an external CRM database (MySQL) in my rails4 app. I am able to connect to the DB through console, and i can use the MySQL2 gem to directly connect and query using this approach:
connection = Mysql2::Client.new(host:11.12.14.14,username...)
results = connection.query("SELECT * FROM.....")
However, I am confused as to how best to implement and reuse this connection. I have concerns about connection pooling and opening too many connections... Through researching this topic I found a lot of information about using a model... So I setup an abstract Model, and put the database connection info in my database.yml
class ExternalCrm < ActiveRecord::Base
# No corresponding table in the DB.
self.abstract_class = true
establish_connection(:external_crm)
def self.getCustomerId(first_name, last_name)
get = connection.select_one("SELECT * FROM customers WHERE First_Name=#{connection.quote(first_name)} AND Last_Name=#{connection.quote(last_name)}")
get.id
end
end
This works... and i can run this method BUT why do i have to call the connection ExternalCrm.connection.select_one() rather than just directly saying ExternalCrm.find_by_sql()... also, will calling connection every time use the pool or could it cause a too many connections issue?
Most of the queries I need to run are just big raw SQL statements, so i don't really need activerecord, and models for each table. So I am not sure if using an abstract model is the best approach here...
My goal is to establish the connection, and then be able to run methods the connection... for example ExternalCrm.getUserId(firstname,lastname)
What would be the best way to accomplish this?
Upvotes: 0
Views: 1811
Reputation: 3699
Reusing connection.
You have already wrapped up in a class, hence a connection will remain open all the time and it's a good approach, and the problem of multiple connections not to be worried.
You haven't specified if you are dealing with multiple table tables with ExternalCrm
connection, if not
self.table_name = 'customers'
would be good then access class with ease ExternalCrm
for using any methods., like,
ExternalCrm.getUserId(firstname,lastname)
In case if tables are changing you could propably reset every connection is completed with the table interaction, with
method.
Check my blog for more.
Upvotes: 1