使用CSV导入更新表 - 要销毁的记录

时间:2013-12-13 01:41:24

标签: ruby-on-rails csv

在我的应用程序中,供应商每天都会为其商店上传库存信息。我目前正在使用find_or_initialize来处理更改的inventory_item属性(特别是价格)。我的问题是,我该如何处理产品停产的情况?显然这些需要从数据库中删除,但有没有办法在不必销毁商店inventory_item记录和导入新的库存CSV文件的情况下做到这一点?

这是我当前的控制器方法:

def import
        InventoryItem.import(params[:file]), params[:store_id]
        redirect_to admin_index_path, notice: "Inventory Imported."
end

这是我的模型方法:

def self.import(file, store_id)

    CSV.foreach(file.path, headers: true) do |row|
    inventory_item = InventoryItem.find_or_initialize_by_code_and_store_id(row[2], store_id])
    inventory_item.update_attributes(:price => row.to_hash["price"])
        end
end

提前致谢!

2 个答案:

答案 0 :(得分:0)

您可以向InventoryItem添加一个布尔“活动”列。然后,供应商只需在新列“活动”中的电子表格中输入true / false即可。在导入期间,您可以更新该属性,并确保商店永远不会显示非“有效”的商品。

答案 1 :(得分:0)

经过深思熟虑,我发现时间戳可能是处理这个问题的好方法。通过将updated_at时间戳与Time.now进行比较,我可以立即销毁相应商店不再提供的库存商品,因此不会在csv导入中更新。如果商店再次获取产品系列,我的模型import方法将只创建一个新记录。这是我的解决方案:

class InventoryItemsController < ApplicationController

    def import
        InventoryItem.import(params[:file], params[:store_id])
        @store = Store.find_by_id(params[:store_id])
        @inventory_items = @store.inventory_items.where('updated_at < ?', Time.now - 1.minute)
        @inventory_items.destroy_all
        redirect_to vendors_dashboard_path, notice: "Inventory Imported."
    end
end

为了确保记录始终在csv导入中更新(即使价格没有改变),我在模型导入方法中更改了这一行:

inventory_item.update_attributes(:price => row.to_hash["price])

到此:

inventory_item.update_attributes(:price => row.to_hash["price"], :updated_at => "#{Time.now}")
相关问题