I need to remove duplicated record on A table and if A table have relation with B table, I should find on B table to record which have removed from duplicated to change other record.
I follow this Remove duplicate records based on multiple columns? that link. This link is works successfully and removed all duplicated records and keep first records on table.
My problem is that when we removed record, that record may used in B table so, I need to find record which is removed and update with the kept record.
def up
grouped = A.all.group_by{|model| [model.name] }
grouped.values.each do |duplicates|
last_one = duplicates.last #also used pop
duplicates.each do |double|
find_in_b = B.find_by(a_id: double.id)
find_in_b.a_id = last_one.id
find_in_b.save!(validate: false)
double.destroy
end
end
end
Thanks in advance!