Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

users.find { |user| user.id == 1 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading