【问题标题】:How to find data between two dates in ruby on rails如何在 ruby​​ on rails 中查找两个日期之间的数据
【发布时间】:2015-12-09 08:19:03
【问题描述】:

查询从现在到3天前的数据不工作。虽然数据存在但无法检索数据。

ViewsLog.where(:created_at=>Time.now..3.day.ago)

ViewsLog Load (0.5ms)  SELECT "views_logs".* FROM "views_logs" WHERE ("views_logs"."created_at" BETWEEN '2015-12-09 08:15:21.586416' AND '2015-12-06 08:15:21.586513')

#<ActiveRecord::Relation []>

【问题讨论】:

  • 应该是3.days.ago 而不是3.day.ago
  • 我试过了,但反应还是一样

标签: ruby-on-rails activerecord


【解决方案1】:

你已经反转了参数 - 它应该是

ViewsLog.where(:created_at=>3.days.ago..Time.now)

【讨论】:

  • 我建议写3.days.ago,因为那是正确的复数形式
【解决方案2】:

你可以这样使用它:

ViewsLog.where("date(created_at) between :start and :end", {start: 3.days.ago.to_date, end: Date.today})

这应该很适合你。

【讨论】:

  • 这是参数化查询。如果我想像上面那样做?
【解决方案3】:

在模型ViewsLog中创建作用域

scope :record_between, lambda {|start_date, end_date| where("created_at >= ? AND created_at <= ?", start_date, end_date )}

scope :record_between, lambda {|start_date, end_date| where(created_at: start_date..end_date )}

现在它对于任何两个日期数据都是通用的

现在你可以做

ViewsLog.record_between(3.day.ago, Time.now)

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多