在Heroku上,我如何安排postgres数据库为我的Rails应用程序定期重置?

时间:2015-06-02 14:04:34

标签: ruby-on-rails postgresql heroku

我正在运行一个小型演示网站。我想一小时左右重置一次数据库(自动,非手动)。我可以编写一个rake任务来销毁每个模型的记录。有更简单的方法吗?

如何最好地完成这项工作?

5 个答案:

答案 0 :(得分:2)

请参考此链接以了解如何在heroku上自动执行rake任务 http://kakimotonline.com/2014/04/27/using-rake-to-automate-heroku-tasks/

你的rake文件看起来像这样:

namespace :heroku do


  def run_command(cmd, app_name)
    Bundler.with_clean_env do
      sh build_command(cmd, app_name)
    end
  end

  def build_command(cmd, app_name)
    "heroku #{cmd} --app #{app_name}"
  end

end

答案 1 :(得分:2)

您可以使用Heroku Scheduler来安排佣金任务。如果你使用foobar_func($json_output)进行任务运行,那么它也适用于调度程序。

答案 2 :(得分:1)

the example关联Akshay之后,我能够让这个工作正常,但不完全符合我的计划。

首先,澄清一下。要在Heroku上添加计划程序加载项,您必须提供您的信用卡号。我仍然在使用Heroku平台,但我还没有做好准备。所以我的解决方案在没有调度程序附件的情况下工作。相反,它从本地开发环境作为rake任务运行,并使用heroku工具带在远程应用程序上运行reset命令。

如果您希望在Heroku上运行所有内容,我认为这不会起作用,因为您无法在Heroku上运行requestLayout()命令。但是,看起来此解决方案here可行。

现在我的解决方案。

首先,创建以下rake文件:

heroku pg:reset

现在,您可以通过使用应用名称从本地环境运行以下rake命令来重置数据库(为您的应用名称运行# lib/tasks/heroku.rake namespace :heroku do # bundle exec rake heroku:reset_db['my-app-name'] # Note: run locally with Heroku toolbelt to reset DB on app desc 'Reset database with seed data' task :reset_db, [:app_name] do |t, args| run_command("pg:reset DATABASE_URL --confirm #{args.app_name}", args.app_name) run_command("run rake db:migrate", args.app_name) run_command("run rake db:seed", args.app_name) end # Helper Functions # Source: http://kakimotonline.com/2014/04/27/using-rake-to-automate-heroku-tasks/ def run_command(cmd, app_name) Bundler.with_clean_env do sh build_command(cmd, app_name) end end def run_command_with_output(cmd, app_name) Bundler.with_clean_env do `#{build_command(cmd, app_name)}` end.gsub("\n", "") end def build_command(cmd, app_name) "heroku #{cmd} --app #{app_name}" end end ):

heroku apps

如果您想安排它像我一样定期运行,请将作业添加到本地crontab(这比复制上面的行稍微复杂一点):

bundle exec rake heroku:reset_db['my-app-name']

有关设置cron作业以使用rbenv运行rake任务的更多信息,请参阅this article

答案 3 :(得分:0)

rake db:schema:load完成了你想要的,虽然我从来没有尝试过在Heroku上运行它。

您还可以尝试database_cleaner gem,它通常用于测试环境。

答案 4 :(得分:0)

试试heroku run rake db:setup。 但是您必须在需要时随时手动运行它。