[Ruby-on-rails] Do rails rake tasks provide access to ActiveRecord models?


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


require 'config/environment'

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


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

And here is what my parent model looks like:

class Parent < ActiveRecord::Base
  has_many :children

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

The :environment dependency is quite correctly called out, but rake still may not know about other gems that your models depend on - in one case of mine, 'protected_attributes'.

The answer is to run:

bundle exec rake test:new_task

This guarantees that the environment includes any gems specified in your Gemfile.