Saving multiple objects in a single call in rails

后端 未结 6 484
無奈伤痛
無奈伤痛 2020-12-12 13:25

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 =&g         


        
6条回答
  •  庸人自扰
    2020-12-12 13:58

    Since you need to perform multiple inserts, database will be hit multiple times. The delay in your case is because each save is done in different DB transactions. You can reduce the latency by enclosing all your operations in one transaction.

    class Foo
      belongs_to  :parent,   :class_name => "Foo"
      has_many    :children, :class_name => "Foo", :foreign_key=> "parent_id"
    end
    

    Your save method might look like this:

    # build the parent and the children
    a = Foo.new(:name => "bar")
    a.children.build(:name => "123")
    
    b = Foo.new("baz")
    b.children.build(:name => "zxy")
    
    #save parents and their children in one transaction
    Foo.transaction do
      a.save!
      b.save!
    end
    

    The save call on the parent object saves the child objects.

提交回复
热议问题