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

Rake task during application initialization rails


I want to execute a rake task when the server of my application starts.

In config/application.rb i put the following:

if !Rails.env.production?
  Rake::Task[ "init:db_records" ].invoke
end 

The rake task is well defined, and runs without a problem if i invode it from terminal

rake init:db_records

But when placed in config/application.rb (or even in any initializers/*) i got the following error.

Don't know how to build task 'init:db_records'

What is the way to execute a rake task when the server starts ?

Thanks!


Solution

  • For those who encounter the same problem in the future.

    I achieved this by creating a new file in the initializers directory, where i put the code of the rake task.

    The advantage of this at this point, is that the application is already loaded, so you have access to ActiveRecord functions...

    Putting the code directly in config/application.rb didn't work, since my models were not loaded yet.

    Hope it will help!