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.
Since it is an array of objects, you should use find
with block:
users.find { |user| user.id == 1 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With