Heroku is a common hosting solution for many Rails projects. Today I’m going to show you how you can ask Heroku to run Rails migrations for you automatically. I will also share the commands you need to run a manual migration.
If you’re just here for the code you need, add this to your
release: rake db:migrate
If you don’t know what a
Procfile is or what that command means, stick around 😊
Heroku uses a text file named
Procfile to let you tell it which web server to use, what workers to run and, importantly for us, which tasks to run before a new release is deployed.
The format of the
Procfile is a list of key: value pairs.
Here is a sample Procfile from one of our projects. It specifies the web server, what to do before a release, and how to run a worker.
web: bundle exec puma -C config/puma.rb release: rake db:migrate worker: bundle exec sidekiq -c 2
We want to run
rake db:migrate before Rails is released because you don’t want people using your application without the correct database setup.
You don’t have to call
rake db:migrate. If you had a script you run that does migrations in a slightly different way, you could call
Running migrations manually
Heroku has a tool that allows you to interact with your application from your computer’s command line, Heroku CLI.
Once installed, you get access to many small tools for interacting with your Heroku application, including
heroku run rake db:migrate --app my_awesome_app
This command will spin up a temporary instance of your application and immediately run
rake db:migrate; once it has completed, Heroku will destroy the temporary instance.
run command is excellent for running a Rails console too;
heroku run rails c --app my_awesome_app
In both of these examples,
--app my_awesome_app refers to the name of the application within Heroku.