Find records that were created closest to the current date

纵饮孤独 提交于 2020-01-01 10:13:27

问题


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?


回答1:


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...

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).

Update: Thanks to Mischa

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

Update

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))


来源:https://stackoverflow.com/questions/12294272/find-records-that-were-created-closest-to-the-current-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!