Find records that were created closest to the curr

2019-04-10 06:43发布

问题:

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