从数组中删除对象而不从数据库中删除它

时间:2016-03-28 13:25:05

标签: ruby-on-rails arrays activerecord

我遇到了一个问题,我只需要从2个活动记录对象数组中删除重复项。唯一的问题是它只是从数据库中删除它,我只需要在这种情况下从数组中删除它。我遵循了这个Remove object from an array of objects并尝试了一些其他的东西,他们能够从内存中删除它并明确地从数组而不是数据库中删除它,但我无法复制它。任何建议都会很棒。谢谢大家!

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

2 个答案:

答案 0 :(得分:4)

如果您不需要记录:

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

答案 1 :(得分:0)

company_link.delete更改为company_links.delete(company_link)

相关问题