【问题标题】:Rails CSV importing where file has headers not in modelRails CSV导入文件的标题不在模型中
【发布时间】:2016-01-23 23:47:38
【问题描述】:

假设一个模型具有以下标头( ID、Name ),但另一个模型具有带有附加标头的 CSV 文件,例如但不限于( ID、Name、Price、Location )。如何更改您的 Model.rb 文件以跳过不存在的标头?

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

【问题讨论】:

    标签: ruby-on-rails ruby csv import


    【解决方案1】:

    以下代码将创建新产品或编辑现有产品。您可以在 find_or_create_by 块中添加所需的属性。

    def self.import(file)
      CSV.foreach(file.path, headers: true) do |row|
        self.find_or_create_by(id: row["id"]) do |product|
          product.name = row["name"]
        end  
      end
    end
    

    如果您只需要 id 和 name,您可以在 rails 4 中执行类似的操作。

    def self.import(file)
      CSV.foreach(file.path, headers: true) do |row|
        self.where(:id => row["id"], :name => row["name"]).first_or_create
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 2011-02-20
      • 2012-10-27
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多