bsky
bsky

Reputation: 20222

Rails - execute rake tasks at startup

I have the following code in config/application.rb

config.after_initialize do

      IndividualProject::Application.load_tasks
      #load File.join(Rails.root, 'lib', 'tasks', 'download_csv.rake')
      Rake::Task[ 'download_csv:get_files' ].invoke
      Rake::Task[ 'download_csv:place_in_database' ].invoke
    end

My problem is that if I try to execute migrations, I get a database error which says that one of tables I'm referencing in the rake task does not exist.

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "currencies" does not exist

I can solve the issue by commenting out the code and then running the migrations. After this, the server runs fine.

However, I want to deploy to Heroku, where I can't comment out the code before running the migrations.

How should I solve this issue? Do I need to place the code somewhere else in the project?

Upvotes: 3

Views: 1686

Answers (1)

Troggy
Troggy

Reputation: 965

Remove your code from config/application.rb and change the web process in Procfile like following:

  web: rake download_csv:get_files && rake download_csv:place_in_database && bundle exec rails server -p $PORT

Change bundle exec rails server -p $PORT with whatever code you use to start your server.

If you don't have Procfile in your project yet, create one and add it to git.

Now your rake tasks will be executed only before starting the server.

Upvotes: 2

Related Questions