在轨道一次调用保存多个对象 [英] Saving multiple objects in a single call in rails

查看:215
本文介绍了在轨道一次调用保存多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在轨是做这样的事情的方法:

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)

这将做这一切只有两个数据库命中。有没有一种简单的方法来做到这一点的轨道,还是我坚持做这一次?

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?

推荐答案

您可以尝试使用Foo.create代替Foo.new。创建创建一个对象(或多个对象),并将其保存到数据库中,如果验证通过,返回得到的对象的对象是否被成功保存到数据库或没有。

You might try using Foo.create instead of Foo.new. Create "Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not."

您可以创建多个对象,像这样的:

You can create multiple objects like this:

# Create an Array of new objects
  parents = Foo.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])

然后,对于每一个家长,你还可以使用创建添加到其关联关系:

Then, for each parent, you can also use create to add to its association:

parents.each do |parent|
  parent.children.create (:child_name => 'abc')
end

我建议你阅读这两个 ActiveRecord的文档和Rails指南上的ActiveRecord查询界面 ActiveRecord关联。后者包含了所有的方法,一类收益的导向,当你声明的关联。

I recommend reading both the ActiveRecord documentation and the Rails Guides on ActiveRecord query interface and ActiveRecord associations. The latter contains a guide of all the methods a class gains when you declare an association.

这篇关于在轨道一次调用保存多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆