Do rails rake tasks provide access to ActiveRecord models? Do rails rake tasks provide access to ActiveRecord models? ruby-on-rails ruby-on-rails

Do rails rake tasks provide access to ActiveRecord models?


Figured it out, the task should look like:

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

Notice the => :environment dependency added to the task


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)


When you begin writing your rake tasks, use a generator to stub them out for you.

For example:

rails g task my_tasks task_one task_two task_three 

You'll get a stub created in lib/tasks called my_tasks.rake (obviously use your own namespace.) Which will look like this:

namespace :my_tasks do  desc "TODO"  task :task_one => :environment do   end    desc "TODO"  task :task_two => :environment do   end    desc "TODO"  task :task_three => :environment do   end  end

All your rails models etc. will be available for the current environment from within each task block, unless you're using the production environment, in which case you need to require the specific models you want to use. Do this within the body of the task. (IIRC this varies between different versions of Rails.)