Search code examples
ruby-on-railsrubyruby-on-rails-3rakerake-task

Custom rake task can't access ActiveRecord data immediately after rake db tasks?


I have a batch of rake tasks that run sequentially:

task :batch_tasks => :environment do
  Rake::Task["db:drop"].execute
  Rake::Task["db:create"].execute
  Rake::Task["db:migrate"].execute
  Rake::Task["db:seed"].execute
  Rake::Task["db:test:prepare"].execute
  Rake::Task["custom_task_1"].execute
end

Here's what's in custom_task_1:

task :custom_task_1 => :environment do
  puts "begin custom task"
  orders = Order.all #three records
  orders.each do |order|
    puts "Do something to Order\n"
  end
  puts "end custom task"
end

When I run the above batch process, here's what happens:

rake batch_tasks
begin custom task
end custom task

But if I run the custom task AFTER the batch process, here's what happens:

rake custom_task_1
begin custom task
Do something to Order
Do something to Order
Do something to Order
end custom task

One thing to note, when I run debugger on rake batch_tasks with a breakpoint after rake db:seed, a check on eval Order.all returns an empty array []. However, Order.all does have data immediately after all of the rake tasks are finished.

What am I missing about rake db:seed and having access to ActiveRecord data in the next task called?


Solution

  • So the quick fix was to move the db:test:prepare line to the end of the batch.

    I believe the problem stemmed from the environment being switched from development to test and then the custom task was running in the last environment, which then had an empty test database.

    The db:seed command probably switches the environment back to dev and the custom task runs against the correct database.

    task :batch_tasks => :environment do
      Rake::Task["db:drop"].execute
      Rake::Task["db:create"].execute
      Rake::Task["db:migrate"].execute
      Rake::Task["db:seed"].execute
      Rake::Task["custom_task_1"].execute
      Rake::Task["db:test:prepare"].execute # <-- Moved after all other tasks
    end