Ruby - CSV 将拆分数据导入不同的表

Ruby - CSV Import split data into different tables

我正在尝试导入带有 rake 任务的 csv 文件。 csv 看起来像这样

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

我的 table 结构看起来像这样

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

这是我的佣金任务

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

如何导入数据并将它们拆分成不同的 tables?

在您的 #each 中创建每个 ActiveRecord 实例,如下所示:

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'])