Rails Rake Task - Access to model class

Jay Godse picture Jay Godse · Mar 10, 2011 · Viewed 16k times · Source

I would like to define a Ruby (1.9.2)-on-Rails(3.0.5) rake task which adds a user to the User table. The file looks like this:

#lib/tasks/defaultuser.rake
require 'rake'
namespace :defaultuser do
  task :adduser do 
    u=User.new
    u.email="[email protected]"
    u.password="password"
    u.save
    u.errors.each{|e| p e}
  end
end

I would then invoke the task as

> rake defaultuser:adduser

I tested the code in the :adduser task in the Rails console, and it works fine. I tested the rake task, running only

print "defaultuser:adduser"

in the body of the task, and it worked fine.

However, when I combined them, it complained, saying

rake aborted!
uninitialized constant User

I tried a

require File.expand_path('../../../app/models/user.rb', __FILE__)

at above the namespace definition in the rake file, but that didn't work. I got

rake aborted!
ActiveRecord::ConnectionNotEstablished

What do I need to do so that I have the same access to the User model class in the Rake task that I have in the Rails console?

Answer

tobinharris picture tobinharris · Mar 10, 2011

You're close :)

#lib/tasks/defaultuser.rake
require 'rake'
namespace :defaultuser do
  task :adduser => :environment do
    ...
  end

Note the use of :environment, which sets up the necessary Rails environment prior to calling the rake task. After that, your User object will be in scope.