Jeff Erickson
Jeff Erickson

Reputation: 3883

Connecting to external database the idiomatic way in RoR?

I am creating a RoR app, and need to connect to my company's MySQL database (which has nothing to do with this app in itself) to gather some data and report it through the RoR app. What is the idiomatic way to connect to this database? I'll just be running some fairly lite select queries off of it, however they often involve table joins. Should I just connect as through this were not a RoR app?

Upvotes: 1

Views: 78

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270599

If your queries are mostly bound to single tables or utilize only a few joins, you can actually define models for them. It would seem that allowing ActiveRecord to operate on them may be the most idiomatic method to do it inside Rails.

First, define the company database in your database.yml

class ExternalDbTable
  # Connect to the db
  establish_connection :connx_from_database_yml

  # Define table if this query is bound to a single table
  set_table_name 'ext_db_table'
  set_primary_key 'pk_column'
end

From there, you can define named_scopes as you would with a Rails model and basically enjoy all ActiveRecord's benefits. If you don't have to access more than a handful of tables on the external db, you can create models for each and define has_many/belongs_to relationships as you normally would in ActiveRecord. However if it is a large number of tables and you have the ability to create a view on the external database, you can create a model pointed to the view which performs the joins for you. Then define named_scopes against the view as necessary.

Upvotes: 1

Related Questions