在 rails 中的一次调用中保存多个对象 [英] Saving multiple objects in a single call in rails
问题描述
我在 rails 中有一个方法可以做这样的事情:
I have a method in rails that is doing something like this:
a = Foo.new("bar")
a.save
b = Foo.new("baz")
b.save
...
x = Foo.new("123", :parent_id => a.id)
x.save
...
z = Foo.new("zxy", :parent_id => b.id)
z.save
问题是,我添加的实体越多,所需的时间就越长.我怀疑这是因为它必须为每条记录访问数据库.因为它们是嵌套的,所以我知道我不能在父母被拯救之前拯救孩子,但我想一次拯救所有的父母,然后是所有的孩子.做这样的事情会很好:
The problem is this takes longer and longer the more entities I add. I suspect this is because it has to hit the database for every record. Since they are nested, I know I can't save the children before the parents are saved, but I would like to save all of the parents at once, and then all of the children. It would be nice to do something like:
a = Foo.new("bar")
b = Foo.new("baz")
...
saveall(a,b,...)
x = Foo.new("123", :parent_id => a.id)
...
z = Foo.new("zxy", :parent_id => b.id)
saveall(x,...,z)
只需两次数据库命中即可完成所有操作.有没有一种简单的方法可以在 Rails 中做到这一点,还是我一次只能做一个?
That would do it all in only two database hits. Is there an easy way to do this in rails, or am I stuck doing it one at a time?
推荐答案
insert_all (Rails 6+)
Rails 6
引入了一种新方法 insert_all,它在单个 SQL INSERT
语句中将多条记录插入到数据库中.
insert_all (Rails 6+)
Rails 6
introduced a new method insert_all, which inserts multiple records into the database in a single SQL INSERT
statement.
此外,此方法不会实例化任何模型,并且不会调用 Active Record 回调或验证.
所以,
Foo.insert_all([
{ first_name: 'Jamie' },
{ first_name: 'Jeremy' }
])
它明显比
Foo.create([
{ first_name: 'Jamie' },
{ first_name: 'Jeremy' }
])
如果您只想插入新记录.
if all you want to do is to insert new records.
这篇关于在 rails 中的一次调用中保存多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!