【问题标题】:Heroku Scheduler rake task abortsHeroku Scheduler rake 任务中止
【发布时间】:2012-09-16 07:27:51
【问题描述】:

我是 Rails 的新手,我第一次想使用 Heroku Scheduler 在我的 Rails 应用程序中运行定期任务。正如Tutorial 中所建议的那样,我在 /lib/tasks/scheduler.rake 中创建了以下 rake 任务

 desc "This task is called by the Heroku scheduler add-on"
task :auto_results => :environment do
    puts "Updating results..."
    @cups = Cup.all
@cups.each do |cup|
    cup.fix_current_results
end
    puts "done."
end

task :update_game_dates => :environment do
    puts "Updating game dates..."
    @cups = Cup.all
@cups.each do |cup|
    cup.update_game_dates
end
puts "done."
end

该任务在我的本地环境中运行良好,但在推送到 Heroku 并运行该任务后,每个都因以下错误而中止:

rake aborted!
undefined method `name' for nil:NilClass

在我看来,Heroku 似乎无法访问数据库,因此无法恢复它可以执行方法的对象。

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails-3 heroku rake scheduler


    【解决方案1】:

    您可以执行以下操作:

    在您的 Cup 模型中使用类方法。然后,您可以使用 rails runner Cup.my_class_methodcommand 调用它,并在 Heroku 调度程序中进行调度。

    # app/models/cup.rb
    class Cup < ActiveRecord::Base
      # Your existing code
    
      ##
      #  Class Methods
      #  that can be run by 'rails runner Cup.my_class_method'
      #  with the Heroku scheduler
      def self.auto_results
        find_each {|cup| cup.fix_current_results}
      end
    
      def self.update_game_dates
        find_each {|cup| cup.update_game_dates}
      end
    end
    

    然后使用 Heroku 调度器调度rails runner Cup.auto_results和rails runner Cup.update_game_dates。

    我在此过程中对您的代码进行了一些优化,如果您有任何问题,请随时询问。

    【讨论】:

    • 感谢您的回答,但这也不起作用,同样的错误。在开发环境中它可以工作,但这已经完成了我的解决方案。感谢代码优化!
    • 嗯。我看不到您的代码库内部,但您是否在您的 fix_current_results 或 update_game_dates 方法之一中有一些类似 cup.name 的代码,其中应该有 self.name 或更短的 name。你可以编辑你的帖子并在那里添加这些方法,然后我可以看看。
    • 我现在没有我的代码,但我稍后会尝试。里面肯定有cup.name 之类的东西,所以这可能是一个很好的提示。为什么在生产中没有self. 时这些方法不起作用?
    • 这是您的命令运行的当前范围的问题。Cup.do_something 是在 Cup 模型上调用的类方法,它们使用 def self.do_something; end 定义。里面的所有东西都将 Cup 模型作为当前范围,所以 find_each 我上面写的实际上是 Cup.find_each。同时在杯子模型的实例上运行@cup.do_this 是在此类实例上调用的方法,它们是用def do_this; end 定义的。当前范围是@cup 对象,您可以通过调用self.name 或self[:name] 来读取和操作它。
    • self 在此实例上读取变量和执行方法时可以省略,因此要读取名称,您可以编写 name (or again: self.name, self[:name]) while for writing you have to use self.name = ... 或 self[:name] = 。 ... name = ...` 将创建一个名为 name 的局部变量。我现在还没有找到一个好的链接,但这里有一个类似于你的问题:stackoverflow.com/questions/10805136/when-to-use-self-in-model
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 2011-12-03
    • 2016-12-18
    • 1970-01-01
    • 2013-10-11
    • 2016-03-23
    • 2016-09-18
    相关资源
    最近更新 更多