我有两个mongoid文档Class1
和Class2
,都有subject
字段
现在我可以按照这个
@class1_subject = Class1.all.group_by {|s| s.subject }
@class2_subject = Class2.all.group_by {|s| s.subject }
现在@ class1_subject包含=>
{
"algebra" => [
#<Class1 _id: 51af35f4066104e046000003, name: "root", subject: "algebra">
],
"algebra-II" => [
#<Class1 _id: 51af3da0066104f448000003, name: "roo2", subject: "algebra-II">
]
}
和@ class2_subject包含=&gt;
{
"algebra" => [
#<Class2 _id: 51af07d606610423e7000002,.........,subject: "algebra">
]
}
结合后,我期待这个结果
{
"algebra" => [
#<Class1 _id: 51af35f4066104e046000003,name: "root", subject: "algebra">,
#<Class2 _id: 51af07d606610423e7000002,.........,subject: "algebra">
],
"algebra-II" => [
#<Class1 _id: 51af3da0066104f448000003, name: "roo2", subject: "algebra-II">
]
}
我该怎么做?
答案 0 :(得分:1)
这可以是近似值:
@class1_subject.keys.each do |key|
@class2_subject[key] ||= []
@class2_subject[key] += @class1_subject[key]
end
@ class2_subject现在有结果