Home > Net >  Adding join model while importing records via csv - Active Record, Rails
Adding join model while importing records via csv - Active Record, Rails

Time:08-24

I'm trying to import a huge amount of records from CSV files. The records contain multiple emails and phone numbers per cell separated by commas.

The lead model parent has two child models emails, phones

I am trying to only have to iterate through the csv file once and have each lead create itself. Then at the same time, create the email and phone number records for the join table.

However, the lead does not yet exist so the self.email will not work. Is there a way of creating all of these three models at the same time?


require 'csv'

class Lead < ApplicationRecord
    has_many :exports
    has_many :emails


    def self.import(file)
        CSV.foreach(file.path, headers: true) do |row|
            lead_hash = Lead.new
            lead_hash.url = row[0]
            lead_hash.alexa = row[1]

  
                # ISSUE HERE LEAD DOES NOT YET EXIST
            unless row[6].empty?
                email_batch = row[6].split(",")[0..1]
                email_batch.each do |e| 
                    self.emails.find_or_create_by(email1: e)
                end
            end
            unless row[7].empty?
                phone_batch = row[7].split(",")[0..1]
                phone_batch.each do |p| 
                    self.phones.find_or_create_by(phone_number: p)
                end
            end

            lead_hash.save


        end
    end




end




CodePudding user response:

You can create the lead, with emails and phones, in memory and save them all like this:

  lead = Lead.new(lead_attributes)
  lead.phones = [Phone.new(phone_attribute), Phone.new(other_phone_attributes)]
  lead.emails = [Email.new(email_attributes, ... etc ]

  lead.save # creates Lead, Phone, and Email objects with the proper associations and foreign keys. 

  • Related