Pages

Monday, February 29, 2016

I want to use Heroku, but my app uses MySQL

Heroku does NOT work with MySQL databases, as everybody knows. But some people, like myself, prefer to have a single database server in his local development environment. And in my case, and in the cases of many others, this database server is a MySQL server.

In fact, I prefer not having PostgreSQL installed in my development environment. Nothing against this database, but I've been working with MySQL for a long time and my development machine is not a state-of-art notebook, but an old Dell Vostro who has seen better days in its life. Installing many database servers with my Fedora 22 would only damage its performance.

How may I, then, use Heroku for deployment?

First of all, create your app using

$ rails new your_app_name -d postgresql

This will generate a Gemfile and a config/database.yml ready to use PostgreSQL.

Now edit your Gemfile and write the following:

group :development, :test do

gem 'mysql'

gem 'byebug'

end

group :production do

gem 'pg', '~> 0.15'

gem 'rails_12factor'

end

This will separate things. MySQL will be used for development and test, in your local machine, while PostgreSQL will be used for production at Heroku. This platform sets RAILS_ENV to production, then this will do the magic for a now. But this is not enough.

Now edit your config/database.yml.

Having created it as said above, you'll have a few lines saying:

default: &default

adapter: postgresql

encoding: unicode

# For details on connection pooling, see rails configuration guide

# http://guides.rubyonrails.org/configuring.html#database-pooling

pool: 5

Don't touch this! Let it be exactly as it is.

Now, right below this you may have your settings for the development environment. Replace them with:

development:

adapter: mysql

username: <your_database_username>

password: '<your_database_password>'

host: localhost

database: <your_database_name>

And do the same for your test environment:

test:

adapter: mysql

username: <your_database_username>

password: '<your_database_password>'

host: localhost

database: <your_database_name>

Now you run

$ bundle install

$ git add .

$ git commit -m "Heroku"

$ git push heroku master

and you are ready!

Now Heroku will accept your deploy and your app will work fine. Maybe you'll just need to run some rake tasks to generate your database and migrate it. I'll teach you to do this in the next article, just in case you don't know.

By the way... You surely noticed the gem rails_12factor installed in production environment. Heroku requires it and it is better to add it to your production environment whenever you are going to use this platform.