在Rails ActiveRecord中Upsert

ActiveRecord是否具有内置的upsertfunction? 我知道我可以自己写,但我显然不想,如果这样的事情已经存在。

Model.find_or_initialize可能会做你想要的。 如果有意义的话,可以使用saveupdate_attributes链接它。

Rails指南中的更多信息。

我刚跑过这个库: https : //github.com/seamusabshere/upsert

我还没有测试过它,但看起来很有希望

还有Model.find_or_create

IMO Upsert机制需要为每个模型进行自定义配置。

因此,最好的解决方案是为模型实现自定义SQL查询,例如

 insert into  (, ..., ) values (, ..., ) on duplicate key update field_x = field_x_value, ... field_z = field_z_value;

我写了一篇关于如何实现这一目标的博客文章。 看看这里 。

您必须编写一个有效的记录扩展名。 它看起来像这样。

 module ActiveRecordExtension extend ActiveSupport::Concern def self.upsert(attributes) begin create(attributes) rescue ActiveRecord::RecordNotUnique, PG::UniqueViolation => e find_by_primary_key(attributes['primary_key']). update(attributes) end end end ActiveRecord::Base.send(:include, ActiveRecordExtension)