Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 820
octavian Avatar asked Mar 11 '26 20:03

octavian


1 Answers

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.

like image 62
Troggy Avatar answered Mar 13 '26 12:03

Troggy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!