Ruby on rails 导入CSV时,如何处理与关联对应的行中的数据?

Ruby on rails 导入CSV时,如何处理与关联对应的行中的数据?,ruby-on-rails,ruby-on-rails-3,csv,import,Ruby On Rails,Ruby On Rails 3,Csv,Import,我正在遵循这一原则,这是直截了当的 问题是它只处理一个csv文件,该文件只包含1个模型中的信息 比如说,我有一个CSV文件,我正试图将它导入我的清单模型。在每一行/列表上都有一个名为Building的列,其中的值实际上是该列表的Building属性的名称(即@listing.Building.name) 我在进口时如何处理这些案件 这是Ryan在Railscast中得到的壁橱,在他的案例中,它位于产品模型上: def self.import(file) CSV.foreach(file.pa

我正在遵循这一原则,这是直截了当的

问题是它只处理一个csv文件,该文件只包含1个模型中的信息

比如说,我有一个CSV文件,我正试图将它导入我的
清单
模型。在每一行/列表上都有一个名为
Building
的列,其中的值实际上是该列表的Building属性的名称(即
@listing.Building.name

我在进口时如何处理这些案件

这是Ryan在Railscast中得到的壁橱,在他的案例中,它位于
产品
模型上:

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    product = find_by_id(row["id"]) || new
    product.attributes = row.to_hash.slice(*accessible_attributes)
    product.save!
  end
end
他正在检查产品是否存在,以及是否存在,然后更新属性。如果没有,那么创建一个新的

不太确定在这种情况下如何处理关联…特别是考虑到需要发生的是在关联记录不存在的情况下,需要在此过程中创建关联记录

所以回到前面的
building.name
示例,如果没有
building.find by_name(name)
,那么它应该创建一个新的building记录

想法?

试试这个

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    product = find_by_id(row["id"]) || new
    product.attributes = row.to_hash.slice(*accessible_attributes)
    product.save!

    building = product.buildings.find_by_name(row['building_name'])
    building ||= product.buildings.build
    building.attributes = row.to_hash.slice(*build_accessible_attributes)
    building.save!
  end
end
更新:使用新的rails 3方法更新答案

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    product = where(id: row["id"])
      .first_or_create!(row.to_hash.slice(*accessible_attributes))

    product.buildings.where(name: row['building_name'])
      .first_or_create!(row.to_hash.slice(*building_accessible_attributes))
  end
end

为什么我会收到此错误消息:
CSV.foreach(file.path,headers:true)do | row |
行中nil:NilClass的未定义方法“path”?当我单击“浏览”按钮时会发生这种情况。你需要为即将出现的问题创建另一个问题,但我想我会先尝试:)完成…你能帮我检查一下吗?请:谢谢。一旦我通过了这个问题,我就可以在这里测试你的答案并接受它是否正确:)首先使用
first\u或\u create
而不是使用
find\u或\u create
成为标准