Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find records that were created closest to the current date

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?

like image 523
chell Avatar asked Sep 06 '12 06:09

chell


1 Answers

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))
like image 61
Baldrick Avatar answered Nov 12 '22 14:11

Baldrick