【问题标题】:When importing a CSV, how do I handle data in a row that corresponds to an association?导入 CSV 时,如何处理与关联对应的行中的数据?
【发布时间】:2013-01-16 12:27:05
【问题描述】:

我正在关注Import CSV Railscast,它是直截了当的。

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

假设我有一个 CSV 文件,我正尝试将其导入到我的 Listing 模型中。在每一行/列表中,它都有一个名为 Building 的列,其中的值实际上是该列表的建筑属性的名称(即 @listing.building.name)。

我如何处理导入中的这些情况?

这是 Ryan 在 Railscast 中获得的壁橱,在他的案例中是 Product 模型:

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),那么它应该创建一个新的建筑记录。

想法?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 csv import


    【解决方案1】:

    试试这个

    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| 行收到此错误消息:undefined method 'path' for nil:NilClass?当我单击“浏览”按钮时会发生这种情况。
    • 您需要为此创建另一个问题
    • 本来打算,但我想我会先试试 :)
    • 完成...你能帮我看看吗:stackoverflow.com/questions/14643449/… 谢谢。一旦我通过了这个问题,我就可以在这里测试你的答案并接受它是否正确:)
    • 使用first_or_create而不是使用find_or_createRails Active Record Query成为标准
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多