Forum: Ruby on Rails saving mutliple objects to database

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Adam A. (Guest)
on 2009-04-09 16:55
If i create in memory a hundred or so instances of a model, how do i go
about saving them to the database.

I have a Task Model

and say I have an array of Task obects

@tasks = [...]

how do i save them

do i

@tasks.each do |task|
task.save
end
?
Wisccal W. (Guest)
on 2009-04-14 18:06
Adam A. wrote:
> If i create in memory a hundred or so instances of a model, how do i go
> about saving them to the database.
>
> I have a Task Model
>
> and say I have an array of Task obects
>
> @tasks = [...]
>
> how do i save them
>
> do i
>
> @tasks.each do |task|
> task.save
> end
> ?

What you can do is use the Model#create class method. You will have to
instantiate hashes of properties instead of model objects, though. Like:

tasks = [{:name => 'Go shopping', :date => Time.now},{:name => 'Get a
haircut' => 1.day.from_now}] #etc
Task.create(tasks)
This topic is locked and can not be replied to.