如何将 2 个活动记录合并在一起并留下 1 条?导轨



我有 2 个苹果:

{
 id: 1,
 rotten: true,
 branch_on_tree: nil,
 type: "red delicious"
},
{
 id: 2,
 rotten: nil,
 branch_on_tree: 5,
 type: "red delicious"
}

它们是红色美味的重复苹果。如何将记录合并在一起,然后删除缺少数据的记录?有没有方便的方法可以做到这一点?

注意:可能有大约 10 个重复项。我不希望我的最终记录中的任何空值。非空值优先。

不是很方便,但它会起作用

假设苹果是一个数组:

[
  {
   id: 1,
   rotten: true,
   branch_on_tree: nil,
   type: "red delicious"
  },
  # ...
]

这可能来自:

apples = Apple.where(type: "red delicious")
apples_attrs = apples.map(&:attributes)

然后

apple_attrs = apples_attrs.reduce do |apple, next_apple| 
                apple.merge(next_apple) do |_, old_value, new_value| 
                  old_value || new_value
                end
              end

apples.destroy_all
Apple.create(apple_attrs)

您可能需要查看本指南 https://apidock.com/ruby/Hash/merge

假设type总是有一些值,你可以将DISTINCTwhere子句一起使用。以下应该有效

Apple.where('rotten IS NOT NULL AND branch_on_tree IS NOT NULL').select('DISTINCT ON (type) rotten,branch_on_tree,type').take

相关内容

最新更新