views:

2068

answers:

2

I am trying to create a custom rake task, but it seems I dont have access to my models. I thought this was something implicitly included with rails task.

I have the following code in lib/tasks/test.rake:

namespace :test do
  task :new_task do
    puts Parent.all.inspect
  end
end

And here is what my parent model looks like:

class Parent < ActiveRecord::Base
  has_many :children
end

It's a pretty simple example, but I get the following error:

/> rake test:new_task
(in /Users/arash/Documents/dev/soft_deletes)
rake aborted!
uninitialized constant Parent

(See full trace by running task with --trace)

Any ideas? Thanks

+1  A: 

you might need to require your configuration (which should specify all your required models etc)

eg:

require 'config/environment'

alternatively you can just require each seperately, but you might have environment issues AR not set up etc)

Luke Schafer
This will work, but it will break rake in general! After adding this change, try rake -T without a DB available. rake -T should happily provide a list of rake tasks without needing access to the DB!
irkenInvader
+20  A: 

Figured it out, the task should look like:

namespace :test do
  task :new_task => :environment do
    puts Parent.all.inspect
  end
end

Notice the '=> :environment' dependency added to the task

gmoniey
ah, of course. easy to miss
Luke Schafer