Abhi
Abhi

Reputation: 4261

Bulk insert data into rails DB with associations

I wanted to copy and bulk insert data to database (using bulk_insert GEM), so I tried the following:

@questionnaires = Questionnaire.where(:id => params[:id])
@new_sections = []

@questionnaires.includes(:sections, :questions).each do |questionnaire|
  questionnaire.sections.each do |section|
    s = section.dup
    s.questionnaire_id = nil
    new_section = Section.new( s.attributes.reject{|k, v| ["id", "created_at", "updated_at"].include?(k)} )
    questions = []

    section.questions.each do |question|
      q = question.dup
      q.section_id = nil
      questions << q.attributes.reject{|k, v| ["id", "created_at", "updated_at"].include?(k)}
    end

    new_section.questions.build(questions)
    @new_sections << new_section
  end
end

Now, here @new_sections has all the sections with associated questions, but is not saved.

SAVING

Section.transaction do
  Section.bulk_insert values: @new_sections.map(&:attributes)
end

But, this only saves the sections but not it's associations. How can I save associations(questions) as well.

EDIT

Now, I came across this https://github.com/zdennis/activerecord-import/wiki GEM and I'm trying the Multi-Level Example, still questions are not saved. Any ideas?

Upvotes: 1

Views: 1202

Answers (1)

Negnar
Negnar

Reputation: 58

I beleive you need to enable ActiveRecord::NestedAttributes (see: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html for reference).

Afterwards you would need to change

section.questions

into

section.questions_attributes

and add

accepts_nested_attributes_for :questions

in Section model

Keep in mind i am not entirely sure how would it work with inserting existing questions as association.

Upvotes: 1

Related Questions