Rails custom rake tasks

While working on migrating a Rails 3 application to Rails 4 I tweaked some of the database tables switching a column from one table to another.

But because the new values are NULL by default trying to display the details of a specific item on the front page (which uses the transferred column via a foreign key reference) would break the page with a message like.

Missing record error Couldn’t find DrShutdownStage without an ID.

Now this is actually very easy to fix with a quick database update but it would be good to be able to encapsulate this within the application build. I decided to look at using a rake task to handle this (although it is capable of so much more).

It’s very easy to use a Rails generator to create a rake task, although it’s as easy to create it from scratch.

The command,

$ rails g task db task_application_shutdown_stage

creates the following file in lib/tasks/db.rake,

namespace :db do
  desc "TODO"
  task task_application_shutdown_stage: :environment do

The name of the rake file doesn’t actually matter.

We can then using standard Ruby code to define the task,

  desc "Set a default for the application shutdown stage"
  task task_application_shutdown_stage: :environment do
    puts "Setting default application shutdown stage"
    dss = 'Green'
    d = ShutdownStage.select(:id).where(:name => dss)
    Application.where(:dr_shutdown_stage_id => nil).each do |app|
      app.update(:dr_shutdown_stage_id => '4')
      puts "Updated #{app.name} with shutdown status #{dss}."

We can then view the task and it’s place among the others with,

rake -T
rake about # List versions of all Rails frame...
rake assets:clean[keep] # Remove old compiled assets
rake db:setup                            # Create the database, load the sc...
rake db:structure:dump                   # Dump the database structure to d...
rake db:task_application_shutdown_stage

And we can run the task with,

$ rake db:task_application_shutdown_stage
Setting default application shutdown stage
Updated roombooking system with shutdown status Green.
Updated expenses system with shutdown status Green.

And the change can be verified with a database query.

As a later stage in our application deployment process comes along we have a simple and reliable task that can be used in a deployment script to configure the application for operational use without relying on manual DB updates.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.