How to find records that have duplicate data using Active Record

后端 未结 6 1253
刺人心
刺人心 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:21

    Here's how I solved it with the AREL helpers, and no custom SQL:

    Person.select("COUNT(last_name) as total, last_name")
      .group(:last_name)
      .having("COUNT(last_name) > 1")
      .order(:last_name)
      .map{|p| {p.last_name => p.total} }
    

    Really, it's just a nicer way to write the SQL. This finds all records that have duplicate last_name values, and tells you how many and what the last names are in a nice hash.

提交回复
热议问题