2
votes

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!

3

3 Answers

1
votes

Rails already has a mechanism for setting up a development database -- rake db:seed. It does not run automatically when you start the app, but it does run as part of rake db:setup.

Unless you have a good reason, it's usually best to stick the conventions that Rails provides.

1
votes

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!

0
votes

Your Rake tasks are (likely) defined in a Rakefile. The initializer has no idea that file even exists, so it doesn't know about the tasks within.

The easiest way to circumvent this is by doing something like this:

Dir.chdir(Rails.root) do
  `rake init:db_records`
end

That is, change the working directory to the root rails directory, then running the command.