Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get and remove duplicate customer #1

Open
nvtin opened this issue Oct 26, 2016 · 0 comments
Open

How to get and remove duplicate customer #1

nvtin opened this issue Oct 26, 2016 · 0 comments

Comments

@nvtin
Copy link
Owner

nvtin commented Oct 26, 2016

Goal:

  • Check and get all customer which is duplicated on database
  • Remove duplicate customers, keep the one which have most fields is not null
  • If all of them have same fields, keep the first.

How to do:

  1. To get customers which have same email
    Customer.select('email, count(email)').group('email').having('count(email) > 1')

  2. Count fields is not null on customer

    def count_present_attributes(customer)
    count = 0
    customer.attributes.keys.each do |k|
      count += 1 if customer.send(k).present? 
    end
    count
    end
    
  3. Destroy duplicate customers

def delete_duplicate_customer
    Customer.select('email, count(email)').group('email').having('count(email) > 1').each do |customer|
      customers_with_dup = Customer.where(email: customer.email)
      customer_to_keep = customers_with_dup.max_by{|cust| count_present_attributes(cust)}
      customers_to_delete = customers_with_dup.reject{|item| item === customer_to_keep}
      customers_to_delete.each(&:destroy!)
    end
 end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant