Ruby on rails 使用CSV导入更新rails数据库记录

Ruby on rails 使用CSV导入更新rails数据库记录,ruby-on-rails,activerecord,csv,Ruby On Rails,Activerecord,Csv,我有以下控制器方法: class InventoryItemsController < ApplicationController def import params.permit(:code, :vendor_id, :price) InventoryItem.import(params[:file]) redirect_to admin_index_path, notice: "Inventory Imported."

我有以下控制器方法:

class InventoryItemsController < ApplicationController

    def import
        params.permit(:code, :vendor_id, :price)
        InventoryItem.import(params[:file])
        redirect_to admin_index_path, notice: "Inventory Imported."
    end
end
class InventoryItemsController
然后调用我的模型方法:

class InventoryItem < ActiveRecord::Base

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

我现在希望能够使用类似的CSV导入方法来更新现有记录(对于价格变化等),仅在
:code
属性唯一时添加新记录。如果只是对一条记录进行简单的更新,我可能会这样做,但我不知道如何通过CSV上传来解决这个问题。请帮忙?提前谢谢

这个答案可能会帮助您:

尝试使用类似以下内容的
find\u或\u initialize\u by\u code
。您的代码看起来像

def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
    my_object = InventoryItem.find_or_initialize_by_code(code)
    my_object.update_attributes(row.to_hash)
end

因此,如果资源不存在,
update\u attributes
将创建一个新记录?不完全是这样。如果它不存在,find_或initialize_by将创建它(初始化它)。有关更多信息,请参阅。在这个网站上,“find_或create_by_动态查找器将返回对象(如果它已经存在),否则将创建它,然后返回它。”编辑:我提到了find_或create_by,这篇文章还讨论了find_或initialize_by。这取决于是否要在此方法之后保存对象。