Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding in array of active record results

I am using active record to create array.

users = User.all.to_a

now I want to later on find with in this array user id: 1

users.find(1)

but it is not giving result but returning everything. How can I search in this result array my selected user id. I can see users is a an array but with in array each record of User object.

If I do following

user.first

it return User object, but I want to search, how can I do it. I understand if I remove to_a then it will work but then it will create another sql query.

like image 808
shahidkamal Avatar asked Sep 13 '25 20:09

shahidkamal


2 Answers

Since it is an array of objects, you should use find with block:

users.find { |user| user.id == 1 }
like image 199
potashin Avatar answered Sep 15 '25 10:09

potashin


User.find(1) is an ActiveRecord::FinderMethod. But when you already loaded all records into memory then those records are transformed into instances of User and stored in an Array. Therefore you need to use find or select which are implemented on Array like this:

users.find { |user| user.id == 1 }   #=> returns the first found record
users.select { |user| user.id == 1 } #=> returns an array with all found record

Keep in mind that database queries are able to use efficient indexes when properly set up. Which makes database queries very fast. When you load all records into memory then those records need to be translated into proper instances. And searching on an array cannot use any index which means it could be (depending on the size of the array) slower than a new database query.

like image 45
spickermann Avatar answered Sep 15 '25 08:09

spickermann