0

I have the results of a search in an instance var called @results. Each item is an album. I have looped over the result set and added all the album parent collection id's to a var called @collections. This is done as below:

 @results.each do |album|
  @collections << album.collection_id
end

@collections = @collections.uniq

I now need to re iterate over the @results and create a child array of each album id that belongs in each collection.

I will then be able to use this to build nice output in my view.

I am rather confused as to how to build that child array of album id's per collection id.

Any help on this?

1 Answer 1

2

I now need to re iterate over the @results and create a child array of each album id that belongs in each collection.

You need to use group_by method :

child_array_by_id = @results.group_by { |album| album.collection_id }
@collections = child_array_by_id.keys
# now iterate
child_array_by_id.each do |id_key, val|
   # your code
end

Now you don't need the below to get the @collection array also. Because child_array_by_id.keys is giving you the same.

@results.each do |album|
  @collections << album.collection_id
end

@collections = @collections.uniq
Sign up to request clarification or add additional context in comments.

1 Comment

That's brilliant. Still trying to wrap my head around how it works but thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.