1

I'm having an issue where I just need to remove the duplicates from 2 array of active record objects. The only thing is it is removing it from the database only and I just need it removed from the array in this case. I followed this Remove object from an array of objects and also tried a few other things and they were able to remove it from memory and explicitly remove it from array and not the database but I'm not able to replicate it. Any suggestions would be great. Thanks all!

company_links       = CompanyLinkType.where(company_id: company_ids, contact_linktype_id: 3)
other_company_links = CompanyLink.where(company_id: company_ids, link_type: 'Twitter')


company_links.each do |company_link|
  other_company_links.each do |other_company_link|
    # checks if id and url match, need to remove obj from company_link array
    if other_company_link.company_id == company_link.company_id && other_company_link.url == company_link.contact_link_url
      company_link.delete
      Rails.logger.info"+++++++++DELETED++++++++++"
    end
  end
end
1
  • If both arrays have same type of objects you can OR two arrays like : company_links || other_company_links it will return same result as you require. Commented Mar 29, 2016 at 10:26

2 Answers 2

5

If you don't need the logging:

company_links = company_links.reject do |company_link|
    other_company_links.any? do |other_company_link|
        company_link.company_id == other_company_link.company_id && other_company_link.url == company_link.contact_link_url
    end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Hey thanks, I'm getting this error though. Any ideas? NoMethodError: undefined method `delete_if' for #<CompanyLinkType::ActiveRecord_Relation:0x0000010b8e2d10>
Ahh, you'll need to use reject, since delete_if/reject! are only defined on Array, not Enumerable. I've updated my answer.
This returns an array not an ActiveRecord Collection
0

Change company_link.delete to company_links.delete(company_link)

1 Comment

hey thanks, but it still removes the entry from the database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.