Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda