All of a sudden I realized I had a whole bunch of interesting samples that I had been playing with in Ruby, Rails, and Heroku sitting on my laptop. My dilema was what to share first? After a little thinking (and a lot of coffee after a late night finishing a strategy/adapter for Omniauth – more to come on that one soon), the first snippet I wanted to share was a requirement I see coming up more and more: How do I use multiple databases with the for Ruby Toolkit?

The use of multiple databases seems to be becoming more and more prevalent, especially in light of the increase in cloud databases which significantly lower to overhead in provisioning database instances. Developers may want to access CRM data from one database, analytics from another, and then use memcache or PostgreSQL for local application storage. Good news, Ruby on Rails makes it easy. I'm going to skip a bunch of the toolkit setup, and assume you have read the Using the Toolkit for Ruby on Heroku article, and jump straight to the code. For our example, we are going to use the database on to retrieve data from a custom object called book, and product information from the automatically provisioned database Heroku provides:



First, we need to setup up salesforce.yml as per the article mentioned above, with the addition of the values retrieved from the Heroku environment variable ENV['DATABASE_URL'] or ENV['SHARED_DATABASE_URL'] specified in yaml format:

With our yaml file setup, we are going to assume that the 'default' database is, as per the setup instructions provided in the Getting Started with the for Ruby article. What this means is that whenever we generate models to use in our Rails app we will need to edit the model to changes the parent class and set at tablename. Here is my example for the custom object 'Book' (standard objects are provided as part of the toolkit remember):

Now let's assume that we keep products in our Heroku provisioned database. We would generate our model as normal, then update the products.rb like so, adding an explicit call to establish_connect to reference our environment we added in salesforce.yml:

That's it. You can now deploy your app to Heroku and use both databases on Heroku and

(Note: I tried using the ENV['SHARED_DATABASE_URL'] environment variable available in Heroku, but ActiveRecord didn't seem to like it. I'd be happy to know if anyone else got it working as I would prefer to use the environment variables directly vs. replicating their value in my yaml file.)




Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS