Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

users.find { |user| user.id == 1 }
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!