Get first and last record

suggest change

Rails 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents