Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda