查找最接近当前日期创建的记录 [英] Find records that were created closest to the current date

查看:98
本文介绍了查找最接近当前日期创建的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取其 created_at 日期最接近当前日期的记录。我该如何使用活动记录的 where 子句?

I would like to get the records that have their created_at date closest to the current date. How can I do this with active records' where clause?

推荐答案

您可以找到过去最接近的记录,例如:

You could find the closest record in the past with something like:

Record.where("created_at <= ?", Date.today).order_by("created_at DESC").limit(1)

类似地,将来最接近的记录

Similarly, you can have the closest record in the future

Record.where("created_at >= ?", Date.today).order_by("created_at ASC").limit(1)

然后比较最接近当前日期的那一个。 ..

And then compare wich one is the closest to current date...

可能有一个针对单个请求的解决方案,但我找不到方法(如果您使用的是SQL Server,则有一种方法DATEDIFF可以帮助您。)

There may be a solution to do it with a single request, but I could not find how (if you're using SQL server, there's a method DATEDIFF that could help).

更新感谢Mischa

如果您确定所有 created_at 都在过去,那么您正在寻找最后一条可以写的记录

If you're sure that all created_atare in the past, you're looking to the last created record, that could be written

Record.order("created_at").last

更新

要获得在同一日期创建的所有记录,然后是最后一条记录:

To get all the records created the same date then the last record:

last_record_date = Record.max(:created_at)
Record.where(:created_at => (last_record_date.at_beginning_of_day)..(last_record_date.end_of_day))

这篇关于查找最接近当前日期创建的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆