When importing a CSV, how do I handle data in a row that corresponds to an association?

后端 未结 1 879
遇见更好的自我
遇见更好的自我 2020-12-29 16:28

I am following the Import CSV Railscast and it is straight forward.

The issue is that it deals with just a csv file containing only information in 1 model in 1 file.

相关标签:
1条回答
  • 2020-12-29 16:39

    try this

    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
    

    UPDATE: updated answers using new rails 3 methods

    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
    
    0 讨论(0)
提交回复
热议问题