Home ActiveRecord joining data from 2 tables with one query without looping
 I have a companies table and a leads table. I am pulling a bunch of leads and need to combine each lead with 2 ID columns from the companies table. I want to keep the companies table as the single source of truth for these ID's (and hence not adding these columns to the leads table where it could get out of sync). Right now I pull all the leads and loop through everyone to add this data. I am assuming there's a more efficient way to do this but I'm not sure how. Can someone help? 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