views:

79

answers:

2

I have an array like this

a = []

a << B.new(:name => "c")
a << B.new(:name => "s")
a << B.new(:name => "e")
a << B.new(:name => "t")

How i can save it at once?

+1  A: 
a.each(&:save)

This will call B#save on each item in the array.

Jordan
And wrap that in a B.transaction to get it all saved in one atomic operation.
Farrel
+3  A: 
B.transaction do
  a.each(&:save)
end

This will create a transaction that loops through each element of the array and calls element.save on it.

You can read about ActiveRecord Transactions and the each method in the Rails and Ruby APIs.

Benjamin Manns