Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Find what is the Oldest Item in a Table

I am trying to find a way to get the oldest created_at value to get the oldest object in the class, so taht I can later manipulate it.

I am trying to add all the items into the array and then get the oldest value, and then convert it back by using the .where active record method to get the object created at that date.

This is what I have so far:

date_array=[]
      buy_requests.each do |buy_request|
        date_array << buy_request.created_at
      end
      date_array.min

But I feel like there are easier ways to do this.

On of the problems I am encountaring is that when I add the date to the array I no longer have the time it was created at, therfore I can no longer use .where once I get the oldest date using .min.

Thank you. Please let me know if I wasn't clear enough.

like image 749
Pabi Avatar asked Feb 10 '23 04:02

Pabi


2 Answers

There's no need to get the earliest timestamp and then the corresponding object, simply:

BuyRequests.order(:created_at).limit(1)

... which would benefit from an index on created_at, or maybe ...

BuyRequests.first

... if your id's are reliably assigned in first-come-first-served order.

You may want to break a tie on equal created_at timestamps with:

BuyRequests.order(:created_at, :id).limit(1)
like image 62
David Aldridge Avatar answered Feb 11 '23 18:02

David Aldridge


The min_by method does exactly what you want:

buy_requests.min_by(&:created_at)

However unless you need to load the requests anyway, it will usually be more efficient to do let the database do the sorting (assuming this is an active record model), by doing something like

ByRequest.order('created_at asc').first
like image 34
Frederick Cheung Avatar answered Feb 11 '23 19:02

Frederick Cheung