Uzair Nadeem
Uzair Nadeem

Reputation: 745

Get duplicate records with group rails

Here is my table StudyFieldOption. I want to get all duplicate records whose count is greater than 1 based on option and study_data_field_id. i.e. Two records are duplicate if they have same value in option and study_data_field_id.

I am trying the following but it is not working for me:

StudyFieldOption.select([:option, :study_data_field_id]).group(:study_data_field_id).having("count(*) > 1")

Upvotes: 0

Views: 826

Answers (2)

Walid Da.
Walid Da.

Reputation: 948

You can try the following:

check = {}
dup_indices = []
StudyFieldOption.all.each do |field|
  unique_str = field.option + field.study_data_field_id.to_s
  if check.value?(unique_str)
    dup_indices << check.key(unique_str)
    dup_indices << field.id
  end
  check[field.id] = unique_str
end
puts dup_indices

Upvotes: 0

Salil
Salil

Reputation: 47472

You can use multiple columns in group

StudyFieldOption.select(:option, :study_data_field_id)
                .group(:option, :study_data_field_id)
                .having("count(*) > 1")

Upvotes: 2

Related Questions