I am trying to kill the records in a table which are duplicates. And my aim is to always delete old ones. It's a rake task.
The main section is similar to below,
TableName.order(updated_at: :asc).each do |record|
next if record.valid?
record.destroy!
end
If there are more than 2 duplicated rows are existing, this loop only deletes one of them and exists.
To understand it I debugged into the loop and watched line-by-line, and ta-da! all works. Probably before the destroy! action is not being done the loop iterates. And probably, it only deletes the last record (not every duplicate group's last item)
Anyways, I can fix it via generating an array to destroy all at once or smth but curious why ruby/ActiveRecord acts like this.
As an answer, detailed explanation of what's going on would be appreciated. Thanks