Combining two different ActiveRecord collections into one

佐手、 提交于 2020-01-03 19:30:32

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/36094710/combining-two-different-activerecord-collections-into-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!