如何实现`upsert` PostgreSQL的在ActiveRecord的? [英] How to implement `upsert` for PostgreSQL in ActiveRecord?
本文介绍了如何实现`upsert` PostgreSQL的在ActiveRecord的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个流的数据,其中包含的类别。我想保持一个类别表,应包含每个类别我遇到一次。
I have a stream of data, which contains categories. I want to maintain a Category table which should contain every category I encounter exactly once.
我想实现一个 ID = Category.upsert(名称)
,这应该是原子(当然),以及 - 如果可能的话 - 不使用的存储过程DB的一面。
I want to implement a id = Category.upsert(name)
, which should be atomic (of course), and - if possible - not use stored procedures on the DB side.
推荐答案
这个怎么样:
class Category < ActiveRecord::Base
...
class << self
def upsert(name)
transaction { self.find_or_create_by_name(name).id }
end
end
end
这篇关于如何实现`upsert` PostgreSQL的在ActiveRecord的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文