如何在rails上的ruby中找到两个日期之间的数据

时间:2015-12-09 08:19:03

标签: ruby-on-rails activerecord

查询从现在到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 个答案:

答案 0 :(得分:2)

您已将参数反转 - 它应该是

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

答案 1 :(得分:0)

你可以像这样使用它:

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

这应该适合你。

答案 2 :(得分:0)

在模型 ABC XYZ 1990-12-09

中创建范围
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 )}