Rails-在启动时执行rake任务 [英] Rails - execute rake tasks at startup
问题描述
我在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
我的问题是,如果我尝试执行迁移,则会收到数据库错误,提示我在rake任务中引用的表之一不存在.
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.
但是,我想部署到Heroku,在运行迁移之前,我无法在其中注释掉代码.
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?
推荐答案
从config/application.rb
删除代码,并在 Procfile 如下:
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
使用用于启动服务器的任何代码更改bundle exec rails server -p $PORT
.
Change bundle exec rails server -p $PORT
with whatever code you use to start your server.
如果您的项目中还没有Procfile,请创建一个并将其添加到git.
If you don't have Procfile in your project yet, create one and add it to git.
现在,仅在启动服务器之前将执行rake任务.
Now your rake tasks will be executed only before starting the server.
这篇关于Rails-在启动时执行rake任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!