Reputation: 81
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
Reputation: 1
Record.maximum(:created_at)
will return Record with last created_at
Upvotes: 0
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
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