Home ActiveRecord joining data from 2 tables with one query without looping

# ActiveRecord joining data from 2 tables with one query without looping

user4539
1#
user4539 Published in September 19, 2018, 9:27 am

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")

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 : "" }