1

I've got models called answers, surveys, questions. Now in a survey, there can be up to 200 questions and so one survey can generate up to 200 answer-models in a page.

The question is: How can I save the array of answers I have in a single db-action and not iterate over the array and save each element individually, which takes a lot of time relatively?

1
  • I found this coffeepowered.net/2009/01/23/… and at the end there's ar-extensions with import. This could be the easiest way to get it fast, since according to commentaries, if you specify the import module for example to myslq, and then do a import, it should do it in one sql-action. Commented Oct 21, 2009 at 12:56

2 Answers 2

1

You can pass the 'belongs_to' relationship an :autosave symbol. This will cause the answers to be automatically saved when you save the parent. Something like this then would probably be what you want:

class Survey < ActiveRecord::Base
  has_many :questions
end

class Question < ActiveRecord::Base
  belongs_to :survey, :autosave
  has_one :answer
end

class Answer < ActiveRecord::Base
  belongs_to :question, :autosave
end

I don't know how exactly this will perform behind the scenes, but it will allow ActiveRecord to optimise the SQL and removes the need for you to iterate explicitly over the relationships.

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

1 Comment

Ok I tried this with :autosave => true. Now I used to do this by calling survey << answer in the iteration, but that saves them at the same time. Now I tried also using survey.answers.build(hash_of_answer_attribues) and then saving the parent, but that gave me the same result: each element is added to the database separately
0

No matter what you do, don't forget to wrap your multiple inserts in a transaction. Will really speed things up.

Comments

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.