删除"重复对象和QUOT; [英] Removing "duplicate objects"

查看:160
本文介绍了删除"重复对象和QUOT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有来自同一类对象的数组,在这里关注的两个属性:名称和created_at

我如何找到数组中相同的名称(考虑的DUP)对象,然后删除数据库中的重复记录。与最近可created_at日期的对象,但是,是必须删除所述一个

解决方案

 看到= []
#sort通过创建日期和迭代
collection.sort({| A,B | a.created_at< => b.created_at})。每做| OBJ |
  如果seen.map(安培;:名).INCLUDE?如果该名称已被视为已经obj.name #check
    obj.destroy!
  其他
    可见<< OBJ#如果不是,将其添加到阵列可见
  结束
结束
 

如果希望做的工作。

Let's say I have an array of objects from the same class, with two attributes of concern here: name and created_at.

How do I find objects with the same name (considered dups) in the array, and then delete the duplicate record in the database. The object with the most-recent created_at date, however, is the one that must be deleted.

解决方案

seen = []
#sort by created date and iterate
collection.sort({|a,b| a.created_at <=> b.created_at}).each do |obj| 
  if seen.map(&:name).include? obj.name #check if the name has been seen already
    obj.destroy!
  else
    seen << obj #if not, add it to the seen array
  end
end

Should do the job hopefully.

这篇关于删除&QUOT;重复对象和QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆