如何使用ActiveRecord对此activerecord关联进行分组,以便我可以清理数据

时间:2017-06-24 00:45:07

标签: ruby-on-rails activerecord

说我有以下关联:

user.apples

=> {
   id: 1,
   kind: "red delicious",
   rotten: true
   branch: nil
},
{
   id: 2,
   kind: "red delicious",
   rotten: nil
   branch: 5
},
{
   id: 3,
   kind: "granny smith",
   rotten: true
   branch: nil
},
{
   id: 4,
   kind: "granny smith",
   rotten: nil
   branch: 3
},
{
   id: 5,
   kind: "fuji",
   rotten: false
   branch: nil
},
{
   id: 4,
   kind: "fuji",
   rotten: nil
   branch: 1
}

因此我需要清理一些重复数据。真的应该只有每个kind的苹果,所以我需要将它们组合在一起,这样我就可以迭代几个彼此重复的苹果并将它们组合起来。我希望我的第一步看起来像这样:

{
 "red delicious" => [{
   id: 1,
   kind: "red delicious",
   rotten: true
   branch: nil
},
{
   id: 2,
   kind: "red delicious",
   rotten: nil
   branch: 5
}],
"granny smith" => [
{
   id: 3,
   kind: "granny smith",
   rotten: true
   branch: nil
},
{
   id: 4,
   kind: "granny smith",
   rotten: nil
   branch: 3
}],
etc...
}

有没有办法进行ActiveRecord类型查询?我希望尽可能多地将工作卸载到数据库中。

1 个答案:

答案 0 :(得分:1)

您可以使用group_by

user.apples.all.group_by(&:kind)

这会给你一个数组,每个kind作为键,数组值包含名称等于散列键的所有苹果:

{
  "red delicious"=>[
    #<Apple:0x007f9cb1cc0ba0 id: 1, kind: "red delicious", rotten: true, branch: nil>,
    #<Apple:0x007f9cb1cc0038 id: 2, kind: "red delicious", rotten: nil, branch: "5">
  ],
  "granny smith"=>[
    #<Apple:0x007f9cb1cb3888 id: 3, kind: "granny smith", rotten: true, branch: nil>,
    #<Apple:0x007f9cb1cb3428 id: 4, kind: "granny smith", rotten: nil, branch: "3">
  ],
  "fuji"=>[
    #<Apple:0x007f9cb1cb3220  id: 5,  kind: "fuji",  rotten: false,  branch: nil>,
    #<Apple:0x007f9cb1cb2f50  id: 6,  kind: "fuji",  rotten: nil,  branch: "1">
  ]
}