Rails:从 CSV 文件导入时通过查找另一列插入关联的 column_id

Rails: insert associated column_id by looking up another column when importing from CSV file

我在 Whosebug 上查看了一些问题,但没有找到我的案例(我觉得这很奇怪,因为我的目标似乎很常见)。

我有两个模型:ProductsCategories 关联如下:

产品有 category_id

CVS 文件包含以下列:

我究竟如何从文件中取出 category_name 并将 category_id 插入产品 table?

我有以下来自 Rails-Casts 的代码:

  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      Response.create! row.to_hash
    end
  end

谢谢!

并非所有事情都必须在一行中完成。您可以为每个 CSV 行执行类似的操作:

category_name = row['category_name']
category = Category.find_by_name(category_name) unless category_name.blank?

Product.create({
  name: row['product_name'],
  price: row['product_price'],
  category: category
))