【问题标题】:Find Most Recent Rails Record In Past查找过去最近的 Rails 记录
【发布时间】:2017-08-16 04:41:16
【问题描述】:

我正在尝试创建一个 Rails 控制器查询,以查找不是将来的列中最新日期的记录(这就是为什么我不能执行简单的order 语句的原因)。我找到了this post,但那里的答案 (MyModel.where("created_at < ?", 2.days.ago)) 引发了一些错误。

我的这个工作正常,但如果有一周开始在未来,它会选择那个,而不是过去最近的一周:

@most_recent = Plan.order("week_starting").last

关于如何在 Rails 中正确执行此操作有什么想法吗?

这是我的整个plans#index 方法:

 def index
    @plans = Plan.where(user_id: current_user.id)
    @plan = Plan.new
    @recent = Plan.order("week_starting").last  <<<THIS LINE
    @recipes = Recipe.where(user_id: current_user.id)
    @monday = Recipe.where(id: @recent.monday)[0]
    @tuesday = Recipe.where(id: @recent.tuesday)[0]
    @wednesday = Recipe.where(id: @recent.wednesday)[0]
    @thursday = Recipe.where(id: @recent.thursday)[0]
    @friday = Recipe.where(id: @recent.friday)[0]
    @saturday = Recipe.where(id: @recent.saturday)[0]
    @sunday = Recipe.where(id: @recent.sunday)[0]
  end

基本上,我需要当前用户的plan,它的week_starting 值最接近Date.today,但仍在过去。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    检查一下

    Plan.where("created_at > ?", Time.now.beginning_of_week).order("week_starting").last
    

    【讨论】:

    • 这可能不是很清楚,但我正在寻找最近的记录,而不是将来。这两天的事情只是另一个问题的一个例子......
    • 使用您的代码(已改编)我认为这会产生类似Plan.where("week_starting &lt; ?", Time.now).limit(1) 的内容,这给了我一个错误,说undefined method week_starting' for #<:activerecord_relation:0x007fdf1c3e0348>`
    • 计划表中是否有 week_starting 字段?
    • 是的。在plans 表中有一个名为week_starting 的列,其类型为date。我使用它而不是 created_at,因为它们并不总是相同的。
    • Plan.where("plans.week_starting
    【解决方案2】:

    这对你有用吗?

    MyModel.where("created_at < ? ", Time.now).order('created_at DESC').first
    

    不知道为什么你有week_starting 以及那是什么。但是要得到过去的最近记录,就足够了

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多