ActiveRecord 是否具有内置的 upsert 功能?我知道我可以自己写,但如果这样的东西已经存在,我显然不想写。
问问题
29652 次
7 回答
22
rails 6 中有一个很棒的新功能:他们添加upsert
了upsert_all
ActiveRecord
于 2019-06-25T17:28:49.317 回答
15
Model.find_or_initialize
可能会做你想做的事。您可以将其与save
或update_attributes
如果有意义的话。
Rails 指南中的更多信息。
于 2011-01-14T20:32:32.067 回答
14
我刚刚跑过这个库: https ://github.com/seamusabshere/upsert
我还没有测试它,但它看起来很有希望
于 2012-06-21T18:51:32.597 回答
2
Rails 6 针对这种情况引入了 create_or_find_by https://github.com/rails/rails/pull/31989
同样对于大量记录,可以使用https://github.com/zdennis/activerecord-import
例子:
Book.import [book], on_duplicate_key_update: [:title]
于 2019-12-20T13:25:26.457 回答
2
IMO Upsert 机制需要对每个模型进行自定义配置。
所以最好的解决方案是为模型实现自定义 SQL 查询,例如
insert into <table> (<field_1>, ..., <field_n>)
values (<field_1_value>, ..., <field_n_value>)
on duplicate key update
field_x = field_x_value,
...
field_z = field_z_value;
于 2016-04-22T10:03:21.827 回答
1
There is also Model.find_or_create
于 2011-01-14T20:50:48.330 回答
-1
我写了一篇关于我们如何实现这一目标的博客文章。在这里查看。
您必须编写一个活动记录扩展。它看起来像这样。
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)
于 2014-08-17T18:53:22.743 回答