【问题标题】:scope on Date.current only updates when Rails restartsDate.current 上的范围仅在 Rails 重新启动时更新
【发布时间】:2013-07-17 07:33:57
【问题描述】:

我有一个托管在 Heroku 上的 Rails 3 应用程序,针对 Postgres 数据库运行。我有一个控制器操作应该生成一个 RSS 提要,但我发现它在应用程序重新启动之前永远不会更新(要么是因为我对 Heroku 做了一个新版本,要么是因为该站点有一段时间处于非活动状态,所以测功机旋转下来并再次备份)。它正在返回不包括新项目的“陈旧”数据。

范围是这样定义的,基于我模型上名为 dateDate.current 的行之间的比较:

class Petition < ActiveRecord::Base
  scope :current, where(["petitions.date <= ?", Date.current]).order("petitions.date DESC")
  scope :published, { :conditions => { :published => true } }
end 

控制器动作是这样的:

class PetitionsController < ActionController::Base

  before_filter :find_diary

  def rss
    current_petitions.each do |petition|
      puts petition.date
    end                
  end

  protected

  def find_diary
    @diary = Diary.find(params[:id])
  end    

  def current_petitions
    @diary.petitions.published.current.limit(25)
  end
end

如您所见,它应该返回所有带有date 的请愿书,即今天或更早。它在 Heroku 控制台上运行良好:Diary.find(15).petitions.published.current.limit(25).first 今天总是给我一个。我可以从日志中看到,每次请求提要时它都会调用 current_petitions 函数。但是,如果我让网站运行 24 小时,那么直到昨天它仍然只显示我的请愿书。如果我发布一个版本来添加任何调试代码,它会突然重新开始工作。

【问题讨论】:

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


    【解决方案1】:

    当您设置一个包含时间的作用域时,您需要使用 lambda 表达式来确保每次使用该作用域时都会计算时间调用。 rails guide 中有更多详细信息,但您的范围需要看起来更像:

    scope :current, lambda { where(["petitions.date <= ?", Date.current]) }
    

    【讨论】:

    • 当你知道怎么做时很容易!
    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多