0

I have an array of id's ["2", "3", "2", "3"] for example.

I'm attempting to iterate through these array elements.

@car = car.first @driver = @car.drivers.first service_ids = ["2", "3", "2", "3"] service_ids.each do |service_id| arr = [] results = @driver.services.find_by(id: service_id) arr << results end 

arr only returns a single record, likely the last record found.

How do you accomplish this? Is there a rails method that does something like this?

Thanks.

4 Answers 4

3

This is happening because you are instantiating the array inside of your block, the following should accomplish what you want:

@car = car.first @driver = @car.drivers.first service_ids = ["2", "3", "2", "3"] results = service_ids.map { |service_id| @driver.services.find_by(id: service_id) } 

Map iterates through your collection, and collects the results of the block with each iteration in an array as the return value.

And actually, ActiveRecord is smart enough to perform a WHERE id IN () query, so the following would be equivalent, and more performant, as it would perform only one query

@car = car.first @driver = @car.drivers.first service_ids = ["2", "3", "2", "3"] results = @driver.services.where(id: service_ids) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this thorough explanation. Really appreciate it!
2

You can also just call find method:

@car = car.first @driver = @car.drivers.first service_ids = ["2", "3", "2", "3"] arr = @driver.services.find(service_ids) 

find accepts an array of ids and returns an array of records.

Comments

1

You can use where instead of find_by for that. You can also try using find_all_by.

Comments

0

Your code is failing because every time you look at another service_id... you reset arr to be an empty array.

if you moved that line: arr = [] outside of the loop, your original code would start working (even if it's not the ideal solution).

As Jeff pointed out, the best solution is to pass the whole set of ids to find - which is smart enough to find a whole set if you do that :)

arr = @driver.services.find(service_ids) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.