Skip to content

Instantly share code, notes, and snippets.

@doluvor
Created October 24, 2016 06:20
Show Gist options
  • Save doluvor/b762cad51b741ef78e5f6b7d2ab317bd to your computer and use it in GitHub Desktop.
Save doluvor/b762cad51b741ef78e5f6b7d2ab317bd to your computer and use it in GitHub Desktop.
Delete duplicated records in Rails
Product.group_by{|x| [x.legacy_id, x.company]}
.flat_map{|_,x| x.drop(1)}
.delete_all
Product.where.not(id: Product.group(:legacy_id, :company).pluck('min(products.id)'))
.delete_all
delete from products
where id not in (
select min(p.id) from products p group by p.legacy_id, p.company
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment