How to find records that have duplicate data using Active Record

后端 未结 6 1255
刺人心
刺人心 2021-01-31 04:12

What is the best way to find records with duplicate values in a column using ruby and the new Activerecord?

6条回答
  •  不思量自难忘°
    2021-01-31 04:33

    Here is a solution that extends the other answers to show how to find and iterate through the records grouped by the duplicate field:

    duplicate_values = Model.group(:field).having(Model.arel_table[:field].count.gt(1)).count.keys
    Model.where(field: duplicate_values).group_by(&:field).each do |value, records|
      puts "The records with ids #{records.map(&:id).to_sentence} have field set to #{value}"
    end
    

    It seems a shame this has to be done with two queries but this answer confirms this approach.

提交回复
热议问题