Search code examples
rubycsvimportrake

Ruby - CSV Import split data into different tables


I'm trying to import a csv file with a rake task. The csv looks like this

model,brand,type,engine,price,doors
Corsa,Opel,cupe,1100,14500,2
Corsa,Opel,cupe,1100,1450,2
Impreza,Subaru,sedan,1200,25000,4

My table structure looks like this though

# Tables
Brands: id, brand_name
Models: id, brand_id, model_name, type_id, engine, price, doors
Types: id, car_type (cupe, sedan etc)

This is my rake task

require "csv"

namespace :import do
  desc "Import cars from CSV"
  task cars: :environment do
    file = File.join(Rails.root, "cars.csv")
    CSV.foreach(file, headers: true) do |row|
      p row
    end
  end
end

How can I import the data and split them into the different tables?


Solution

  • Inside your #each create each ActiveRecord instance like this:

    brand = Brand.find_or_create_by(brand_name: row['brand'])
    type = Type.find_or_create_by(car_type: row['car_type'])
    Model.create(
      brand: brand,
      type: type,
      model_name: row['model_name'],
      engine: row['engine'],
      price: row['price'],
      doors: row['doors'])