将两个不同的ActiveRecord集合合并为一个
我想为所有公司事件创建一个可视的时间表。时间轴的HTML使用循环
构建。
I want create a visual timeline of all company events. The HTML for the timeline is built using a loop
.
为简单起见,我们假设两个模型雇用
& 交易
。两种模型都具有 date
属性和某些模型特定的属性。如何合并两个模型的 ActiveRecord
结果,然后 order
合并的哈希值按合并日期
,放入一个我可以循环通过的哈希?
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?
假设结果同时查询 Hire
和 Deal
模型是对象数组( collection ),然后您只需使用 +
将它们连接成一个新数组,并在日期
之前使用 sort_by
:
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)
或使用 concat
将一个集合与另一个集合连接:
or use concat
to concatenate one collection with another:
combined = Hire.all.concat( Deal.all ).sort_by(&:date)