Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do rails rake tasks provide access to ActiveRecord models?

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

like image 490
gmoniey Avatar asked May 18 '09 05:05

gmoniey


People also ask

What are Rake tasks in Rails?

Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.

How to write Rake task in Rails?

If you want to write your own rake task you have 2 ways to do it (I thought so before): Write it from scratch. Copy-paste code from another ready rake task and change code to required.

Where is Rake task?

Summary. You have learned about Rake, a popular task runner for Ruby. Use rake -T to find out what tasks are available, create your own tasks & add them to the Rakefile , or inside the lib/tasks folder, and remember that Rake & Rack are different things.


1 Answers

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

like image 159
gmoniey Avatar answered Oct 25 '22 23:10

gmoniey