Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two different ActiveRecord collections into one

I want create a visual timeline of all company events. The HTML for the timeline is built using a loop.

For simplicity let's assume two models Hire & Deal. Both models have a date attribute and some model specific attributes. How do I merge the ActiveRecord results of both models, and then order the combined hash by date, into a single hash that I can loop through?

like image 290
Matthias Avatar asked Mar 18 '16 21:03

Matthias


1 Answers

Well, assuming that the result of querying both Hire and Deal models is an array of objects (collection), then you just use + to concatenate them into a new array and sort items by date with sort_by:

combined = ( Hire.all + Deal.all ).sort_by(&:date)

or use concat to concatenate one collection with another:

combined = Hire.all.concat( Deal.all ).sort_by(&:date)
like image 187
potashin Avatar answered Nov 12 '22 10:11

potashin