Noname
Noname

Reputation: 81

Find last created_at record

How can I find the last record by their created_at field?

Record.order("created_at").last

or

Record.where(:created_at).last

or

Neither and there is a better way?

Upvotes: 3

Views: 5276

Answers (3)

Stanislav Timanov
Stanislav Timanov

Reputation: 1

Record.maximum(:created_at) will return Record with last created_at

Upvotes: 0

fl00r
fl00r

Reputation: 83680

That's a valid request

Record.order(created_at: :desc).first

take care of a tree index on this field to have a better performance, though

Upvotes: 5

Cryptex Technologies
Cryptex Technologies

Reputation: 1163

In Rails, you can also add the line

default_scope { order(created_at: :asc) } 

to the Record model to ensure that Record.last behaves as expected you can find the newest record

You can refer the link scopes in rails

Upvotes: 3

Related Questions