Rails - execute rake tasks at startup

a 夏天 提交于 2019-12-10 17:57:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/30411027/rails-execute-rake-tasks-at-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!