Pabi
Pabi

Reputation: 994

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.

Upvotes: 6

Views: 7013

Answers (4)

Collin Graves
Collin Graves

Reputation: 2257

You can very easily use Ruby's sort_by method.

objects.sort_by { |obj| obj.attribute }

So for your example it would be:

buy_requests.sort_by { |req| req.created_at }

Upvotes: 0

David Aldridge
David Aldridge

Reputation: 52346

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)

Upvotes: 8

Frederick Cheung
Frederick Cheung

Reputation: 84114

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

Upvotes: 3

user5067463
user5067463

Reputation:

Why not just use the #first mehod on the Model, if all you care about is the oldest created_at object. I assume the id is are generated sequentially. ie 1, 2, 3, 4

buy_requests.first

will get you the oldest BuyRequest instance you have.I assume the object BuyReuest is an ActiveRecord object

Upvotes: -1

Related Questions