views:

54

answers:

2

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.

+1  A: 
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.

Jakub Hampl
there was syntax error here, but i got it to work. thx!
keruilin
Oh, sorry, missed that one, should be fixed now.
Jakub Hampl
A: 

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
)
Mladen Jablanović