Hopeanuoli
Hopeanuoli

Reputation: 17

How to save an array of models in Rails

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?

Upvotes: 1

Views: 1247

Answers (2)

alex.zherdev
alex.zherdev

Reputation: 24164

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

Upvotes: 0

workmad3
workmad3

Reputation: 25677

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.

Upvotes: 1

Related Questions