Remove duplicate records based on multiple columns?

前端 未结 7 2078
灰色年华
灰色年华 2020-12-04 07:46

I\'m using Heroku to host my Ruby on Rails application and for one reason or another, I may have some duplicate rows.

Is there a way to delete duplicate records base

7条回答
  •  Happy的楠姐
    2020-12-04 08:09

    You could try the following: (based on previous answers)

    ids = Model.group('name, year, trim').pluck('MIN(id)')
    

    to get all valid records. And then:

    Model.where.not(id: ids).destroy_all
    

    to remove the unneeded records. And certainly, you can make a migration that adds a unique index for the three columns so this is enforced at the DB level:

    add_index :models, [:name, :year, :trim], unique: true
    

提交回复
热议问题