Get first and last record
suggest changeRails has a simple way to get the first and last records from the database. With no explicit order, first and last order by the primary key.
To get the first record from the users table:
User.first
That runs:
SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
and returns a record like:
#<User:0x007f8a6db09920 id: 1, first_name: "foo", created_at: Thu, 16 Jun 2016 21:43:03 UTC +00:00, updated_at: Thu, 16 Jun 2016 21:43:03 UTC +00:00 >
To get the last record from the users table:
User.last
That runs:
SELECT `users`.* FROM `users` ORDER BY `users`.`id` DESC LIMIT 1
and returns a record like:
#<User:0x007f8a6db09920 id: 10, first_name: "bar", created_at: Thu, 16 Jun 2016 21:43:03 UTC +00:00, updated_at: Thu, 16 Jun 2016 21:43:03 UTC +00:00 >
Passing an integer to first or last sets LIMIT and returns an array.
User.first(5)
That runs:
SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 5
And:
User.last(5)
That runs:
SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 5
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents