I want to execute two rake tasks which initialise my database when the server starts.
Therefore, I placed the following code in config/application.rb
:
config.after_initialize do
Rake::Task[ 'download_csv:get_files' ].invoke
Rake::Task[ 'download_csv:place_in_database' ].invoke
end
However, I get the following error:
.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task_manager.rb:62:in `[]': Don't know how to build task 'download_csv:get_files' (RuntimeError)
What am I doing incorrectly? (My objective is to initialise the database at startup).
Rails tasks are not automatically loaded, you need to load them first:
config.after_initialize do
Rails.application.load_tasks # <---
Rake::Task['download_csv:get_files'].invoke
Rake::Task['download_csv:place_in_database'].invoke
end
Note that #load_tasks
doesn't store state and if you call it again somewhere else you can experience problems.
On the other hand, the names of the tasks suggest that they don't need to be run on every web instance (e.g. Heroku Dynos); but they will run on each machine using the above strategy. So if you have scaled your web instances (running your app on more than one machine), running these tasks in a single instance (a one-off Dyno on Heroku) as an automated after-deploy task would be more effective.
download_csv:place_in_database
implies there is a task named place_in_database
within a namespacedownload_csv
. Is this how your Rake task looks? It would be much easier diagnose the problem if you post the code.
Also, ensure that your .rake
files reside in lib/tasks
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With