【问题标题】:ActiveRecord Import - duplicate key value violates unique constraintActiveRecord 导入 - 重复键值违反唯一约束
【发布时间】:2019-11-25 06:02:32
【问题描述】:

尝试使用 ActiveRecord 导入更新大型数据集时,我很难理解插入失败的原因。

在我的模型架构中,存在这一行:

t.index ["variant_id", "stock_location_id"], name: "index_spree_stock_items_on_variant_id_and_stock_location_id", unique: true, where: "(deleted_at IS NULL)"

对于导入,我正在尝试更新其中的许多,当我运行时:

Spree::StockItem.import columns, values, :on_duplicate_key_update => [:count_on_hand]

我收到:

duplicate key value violates unique constraint "index_spree_stock_items_on_variant_id_and_stock_location_id"

但是当我跑步时:

Spree::StockItem.import columns, values, :on_duplicate_key_update =>{ conflict_target: [:index_spree_stock_items_on_variant_id_and_stock_location_id], columns: [:count_on_hand] }

我收到:

column "index_spree_stock_items_on_variant_id_and_stock_location_id" does not exist

为什么说这个栏目不存在?索引是否不被视为可用于重复键检查的列?我应该如何通过由两列组合而成的索引来检查重复项?

谢谢

【问题讨论】:

    标签: ruby-on-rails postgresql spree solidus activerecord-import


    【解决方案1】:

    像这样为conflict_target 使用列名而不是索引名

    Spree::StockItem.import(
      columns,
      values,
      on_duplicate_key_update: {
        conflict_target [:variant_id, :stock_location_id],
        columns: [:count_on_hand]
      }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2020-03-27
      • 2013-06-23
      • 2016-06-12
      • 2013-03-15
      • 2016-11-27
      • 2018-03-14
      相关资源
      最近更新 更多