ActiveRecord 将来自 2 个表的数据与一个查询连接而不循环

ActiveRecord joining data from 2 tables with one query without looping

我有一个公司 table 和一个潜在客户 table。我正在收集大量线索,需要将每个线索与公司 table 的 2 个 ID 列组合起来。我想将公司 table 作为这些 ID 的唯一真实来源(因此不会将这些列添加到可能不同步的潜在客户 table 中)。

现在我收集所有线索并循环遍历每个人以添加此数据。我假设有一种更有效的方法可以做到这一点,但我不确定如何做。有人可以帮忙吗?

leads = @user.find_leads(start_date: start_date, end_date: end_date).leads('true').includes(:company).select(fields).limit(limit).offset(offset).order("created_at DESC")

leads.each do |l|
    company = l.company.present? ? l.company.company_external_id : ""
    distributor = l.company.present? ? l.company.mfg_distributor_id : ""
    lead_data = l.attributes.merge({external_company_id: company, external_distributor_id: distributor})
    final_lead = lead_data.each_with_object({}) { |(k,v),g| g[k] = (Hash === v) ? denilize(v) : v ? v : "" }
    all_leads << final_lead.stringify_keys
  end
lead_data = @user.find_leads(start_date: start_date, end_date: end_date).leads('true')
                 .left_outer_joins(:company)
                 .select(fields)
                 .select("companies.company_external_id AS external_company_id, companies.mfg_distributor_id AS external_distributor_id")
                 .limit(limit).offset(offset).order("created_at DESC")
                 .map(&:attributes)
final_lead = ...
all_leads << ...