Miguel Peniche
Miguel Peniche

Reputation: 1032

Getting a record from a collection

I want to get the user_5 (which is the user with id 5) from the users collection.

users = User.all
user_5 = ???

I know I can get it with user = User.find(5) but I don't want to make another query.

Any ideas?

Upvotes: 0

Views: 199

Answers (2)

mrzasa
mrzasa

Reputation: 23307

Calling

users = User.all

does not execute the query. The query is executed when you try to iterate over the collection in find method It may be faster to call

users.find(5)

than using in memory find because it will fetch all the records from database and iterate over them linerly:

users.find { |user| user.id == 5 }

Also users.find may in fact call the AR find not Enumerable#find, so the about example could return nothing, it's safer to use #detect

Upvotes: 1

yoones
yoones

Reputation: 2474

You can use #find:

users = User.all
user_5 = users.find { |user| user.id == 5 }

Upvotes: 2

Related Questions