使用bulk_insert更新Rails中的记录

时间:2018-01-27 18:09:13

标签: ruby-on-rails activerecord

如果我的模型有3个参数:season:player :total_pts

当我致电Model.create(seaon: 2018, player: 123, total_pts: 100)时,我希望任何已经存在seasonplayer的记录被“覆盖”;或者如果它不存在则创建一个新的

我正在使用可能使事情复杂化的bulk_insert宝石

在rails中处理此问题的最佳方法是什么?在搜索时,我找到find_or_create_by并将before_create放入模型中。

我的代码看起来像这样

array_of_full_hashes = [{seaon: 2018, player: 123, total_pts: 100}, {seaon: 2018, player: 444, total_pts: 25}]
Model.bulk_insert do |worker|
 array_of_full_hashes.each do |attrs|
  worker.add(attrs)
 end
end

1 个答案:

答案 0 :(得分:1)

它看起来像bulk_insert gem的PostgreSQL适配器代码takes no action when there's a conflict。但你可以推出自己的冲突解决策略; docs here