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