Ronan Lopes
Ronan Lopes

Reputation: 3380

Rails Active Record - Save multiple objects at once

I took a look a this question and didn't found any answer that worked for me.

I have, for example a Project model, which has_many tasks. I would like to create, from an array of attributes, many tasks for some project. So, in my project model, I would have a method like this (simplified example):

def create_tasks(tasks)
   tasks.map{|t| Task.create(project: self, name: t.name)}
end

The problem is, for each task, it will make a hit on my db, and for a large number of records that wouldn't be desirable. How could I do that so ActiveRecord will make only one call to my database? Thanks in advance!

Upvotes: 3

Views: 2823

Answers (1)

Mikhail Katrin
Mikhail Katrin

Reputation: 2384

Each call for insertion into database will be done separately (in different transactions). But you could decrease a total delay wrapping all creations in a single transaction.

Task.transaction do
    tasks.each{ |task| Task.create(...) }
end

In this case all your creations will be wrapped in one atomic db transaction.

Take a look at transaction documentation.

Also you could try accepts_nested_attributes_for.

Nested attributes allow you to save attributes on associated records through the parent.

Hope it helps.

Upvotes: 5

Related Questions