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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With