0

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?

Randy Burgess
  • 4,835
  • 6
  • 41
  • 59

2 Answers2

1

As mu is too short suggested, this is related to the need to reload models before using them in migrations. The reason for this is that all of your rake tasks run in a common environment, ie, it only loads rails once. As such, the table definitions may already be established. You will probably have to use reset_column_information to load the new values.

Alternately, the sequence of tasks you are doing look like they should be run independently, which could be a good use case for capistrano or thor.

DGM
  • 26,629
  • 7
  • 58
  • 79
  • In this scenario, wouldn't the rake db:seed fail? It's succeeding, the subsequent rake tasks just can't access the data for some reason. – Randy Burgess Sep 11 '12 at 03:12
  • found the issue...your answer wasn't the solution, but it did cause me to mess around with the code in a different way. – Randy Burgess Sep 11 '12 at 03:38
0

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
Randy Burgess
  • 4,835
  • 6
  • 41
  • 59