SinGar
SinGar

Reputation: 111

Rails: Fetch nth table record

I know I can find the first user in my database in the command line with,

User.first

And I can find the last with

User.last

my question is how would I call the 11th user in a database.

Upvotes: 1

Views: 132

Answers (3)

user483040
user483040

Reputation:

You can do:

User.limit(1).offset(10)

That reduces the work to a SQL statement that looks like this:

SELECT  `users`.* FROM `users`  LIMIT 1 OFFSET 10

Using all will require loading all the users into memory and then finding the 11th one in that array. Quite pricey.

Upvotes: 2

Kumar
Kumar

Reputation: 3126

You can do

User.all[10]

User.all gives you an array or objects with index starting from 0. To access 11th user you can do that.

Upvotes: -2

potashin
potashin

Reputation: 44611

You can use offset with order:

User.offset(10).order(:id).first

Upvotes: 2

Related Questions