Find entries created closest to current date

I would like to get records that have a created_at date closest to the current date. How to do this with the suggestion of active where entries?

+4
source share
1 answer

You could find the nearest entry in the past with something like:

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

Similarly, you may have the nearest entry in the future.

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

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

There may be a solution to do this with a single query, but I could not find how (if you are using a SQL server, there is a DATEDIFF method that could help).

Update : thanks Mischa

If you are sure that all created_at in the past, you are looking for the last created record that can be written

 Record.order("created_at").last 

Update

To get all records created for the same date as 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)) 
+7
source

Source: https://habr.com/ru/post/1432639/


All Articles