Ruby on Rails ActiveRecord Query Interface Get first and last record

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Rails have very easy way to get first and last record from database.

To get the first record from users table we need to type following command:

User.first

It will generate following sql query:

SELECT  `users`.* FROM `users`  ORDER BY `users`.`id` ASC LIMIT 1

And will return following record:

#<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 users table we need to type following command:

User.last

It will generate following sql query:

SELECT  `users`.* FROM `users`  ORDER BY `users`.`id` DESC LIMIT 1

And will return following record:

#<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 and last method creates a LIMIT query and returns array of objects.

User.first(5)

It will generate following sql query.

SELECT  "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 5

And

User.last(5)

It will generate following sql query.

SELECT  "users".* FROM "users"  ORDER BY "users"."id" DESC LIMIT 5


Got any Ruby on Rails Question?