3

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!

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I'm gonna do that. Also, do you think that would be good to use threads for doing each insert?
also, there's a typo on "create"
If you're talking about Thread, they are for concurrent (not parallel) programming. You won't get any profits of using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.