Skip to content

Instantly share code, notes, and snippets.

@jgrannas
Last active August 29, 2015 14:15
Show Gist options
  • Save jgrannas/4b1c326f72f6b1c0c35d to your computer and use it in GitHub Desktop.
Save jgrannas/4b1c326f72f6b1c0c35d to your computer and use it in GitHub Desktop.
Connecting an external DB with Rails4 model using abstract class and establish connection
#THIS WAS ADDED BELOW OTHER DB CONFIGS
ext_database:
adapter: mysql2
host: 111.111.111.111
database: db_name_here
username: User
password: XXXXX
class MyModel < ActiveRecord::Base
# No corresponding table in the DB.
self.abstract_class = true
establish_connection(:ext_database)
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
@jgrannas
Copy link
Author

This works, however I am unsure if this is the best approach.

I can run MyModel.getCustomerId("John", "Smith") and it returns the first result

My main need for this is just to execute some raw SQL queries (much more advanced than what is in the "getCustomerID" example. My client has a database (CRM) system that I need to lookup customers in.

I still do not really understand why I have to explicitly call MyModel.connection.select() rather than just being able to do a direct MyModel.find(1) --- Also I had to use connection.quote() to prevent sql injections as i could not find a solution for using prepared statements with the MYSQL2 gem.

I have also tried using the MySQL2 gem directly, which works... but I wasn't sure if that could cause a bunch of concurrent and unclosed connections to the database. I also wasn't sure of the best place to initialize that connection, or how to best use this, maybe a service object?

MyDatabase = Mysql2::Client.new(host:"IP.addy", username:"User", password:"XXX", database:"db_name")
results = MyDatabase.query(sql_query_here)

What I ultimately need is a Class, with a bunch of methods... all interacting (querying) the external database. So say from multiple different rails controller I could call ExtDatabase.find_user("John","Smith") as well as ExtDatabase.create_user("John","Smith") or ExtDatabase.update_user(19). A model seems like an "ok" but i feel like there might be a better way of doing this, since i really don't need activerecord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment