Reputation: 1032
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
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