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

ActiveRecord joining data from 2 tables with one query without looping

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

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
share|improve this question

1 Answer 1

active oldest votes
up vote 0 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.251009 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO