How to find records that have duplicate data using Active Record

srboisvert picture srboisvert · Feb 24, 2011 · Viewed 26.2k times · Source

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

Answer

fl00r picture fl00r · Feb 24, 2011

Translating @TuteC into ActiveRecord:

sql = 'SELECT id, 
         COUNT(id) as quantity 
         FROM types 
         GROUP BY name 
       HAVING quantity > 1'
#=>
Type.select("id, count(id) as quantity")
  .group(:name)
  .having("quantity > 1")