Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save an active records array

Tags:

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?

like image 847
Luca Romagnoli Avatar asked Feb 18 '10 22:02

Luca Romagnoli


People also ask

What does active record save return?

Method: ActiveRecord::Persistence#save Saves the model. If the model is new a record gets created in the database, otherwise the existing record gets updated. By default, save always run validations. If any of them fail the action is cancelled and save returns false .

What is MVC active record?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is Active Records in Rails?

Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model, which is as follows − tables map to classes, rows map to objects and. columns map to object attributes.


1 Answers

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.

like image 91
Benjamin Manns Avatar answered Sep 19 '22 08:09

Benjamin Manns