如果我的模型有3个参数:season
,:player
:total_pts
当我致电Model.create(seaon: 2018, player: 123, total_pts: 100)
时,我希望任何已经存在season
和player
的记录被“覆盖”;或者如果它不存在则创建一个新的
我正在使用可能使事情复杂化的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
答案 0 :(得分:1)
它看起来像bulk_insert gem的PostgreSQL适配器代码takes no action when there's a conflict。但你可以推出自己的冲突解决策略; docs here