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 delete开发者_开发技巧d.
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.
If this is just a one-time bugfix before introducing UNIQUE INDEX on the table, you might as well do it in SQL:
DELETE FROM t WHERE id IN (
SELECT t1.id
FROM t t1
LEFT JOIN t t2 ON t1.name = t2.name AND t2.created_at < t1.created_at
WHERE t2.id IS NOT NULL
)
精彩评论