ironsand
ironsand

Reputation: 15151

How to find all models except latest one

I have a Model Foo that have date column, and I want find all foos except for latest one.

foo = Foo.order(:date).last
foos = Foo.where.not(id: foo.id)

I could get the foos with this, is there better way to do it?

Upvotes: 2

Views: 52

Answers (1)

Wes Foster
Wes Foster

Reputation: 8900

The simplest ways to achieve this result would be to query all records, then strip off the last record from the array:

foo = Foo.order(:date).all
foo.pop #Remove the last record from the returned array of records

This will work, however, you need to ensure that your query sorts/orders the returned records accordingly.

Another concise way to do this is:

foo = Foo.order(:date).all[0..-2]

Upvotes: 1

Related Questions