Reputation: 7210
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?
Upvotes: 0
Views: 55
Reputation: 118271
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
Upvotes: 2