views:

128

answers:

3

Hello!

I've been googling this for a while, but haven't found any answers

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  A: 

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.

workmad3
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
Hopeanuoli
A: 

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

neutrino
A: 

Look at the Nested Object Forms

http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

Mike
I need to a lot of modifications to my site, in order to try this out, but I'll get back to this thread after I've done so.
Hopeanuoli