The Life‑Changing Magic of Ruby and Rails

How to Access Rails ActiveRecord Models Inside a Rake Task

If you’ve been working with Ruby on Rails for a while, you’ve come across Rake. Written by the late Jim Weirich, Rake is to Ruby what Make is to C. It’s very easy to create custom Rake tasks to simplify your development workflows. Rails even provides a generator (rails g task) to create them for you.

However, one question that many new Rails developers (including myself) have when learning Rails is how to access the Rails environment in a Rake task, which is very useful for accessing the ActiveRecord models or performing database queries. This article shows how to do it.

TL; DR

Add the :environment task as the dependency for your custom task.

task count_users: [:environment] do
  ...
end

Long Answer

Here’s a simple Rake task that tries to use an ActiveRecord model named User

# lib/tasks/transport.rake

desc "count the number of users in the system"
task :count_users do
  puts User.count
end

If I try to run this Rake task as it is, Rails will throw a NameError, as it doesn’t know what the token User refers to.

bin/rails count_users
rails aborted!
NameError: uninitialized constant User

  puts User.count
       ^^^^^^^^^^^^^^^

To make the ActiveRecord models available in the Rake tasks, we need to tell Rails to load the environment before running the task. This is similar to what happens when you launch the Rails console. Loading the Rails environment gives access to the ActiveRecord models, database, and much more.

Rails provides an :environment task to load the environment. In Rake terminology, your task is dependent on the :environment task, as it must be performed before your task.

# lib/tasks/transport.rake

desc "count the number of users in the system"
task count_users: [:environment] do
  puts User.count
end

Now you can access the User model in the rake task without any errors.

Subscribe to Akshay's Blog

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe