Search code examples
ruby-on-railsrubyruby-on-rails-3.1

Trying to process duplicate activerecord results


I was trying to write a method in ruby that could:

  1. Query through and find all of the duplicates in our DB that meet a certain criteria (first name, last_name, account_id, and title all match)
  2. Iterate through them and combine the contents of a field called possible_unique_keys for all duplicates
  3. Remove the duplicate records now that we have 1 record for each with the concatenated field

I started with a quick query to pull out only the dup candidates:

results = ActiveRecord::Base.connection.select_all( "SELECT id, first_name, last_name, title, account_id, possible_unique_keys, device_contacts_count FROM CONTACTS AS a WHERE 1 < (SELECT Count(*) FROM CONTACTS AS b WHERE b.first_name = a.first_name AND b.last_name = a.last_name AND b.title = a.title AND b.account_id = a.account_id)" )

It pulls out what appears to be the correct results set with the fields that I need. The first problem comes when I try to iterate through them:

results.each do |contact|
  contact.first_name
end

I'm really just getting started trying to get my head around this problem but I get an error when I try to reference any of the fields as I did above when trying to reference the first_name:

NoMethodError: undefined method first_name for #<Hash:0x00000006641cb0>


Solution

  • Returns an array of record hashes with the column names as keys and column values as values.

    contact[:first_name] 
    

    or

    contact["first_name"]