Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4616

import with recursive using activerecord-import gem: has_many through association not working

$
0
0

Trying to import CSV file to the database using "activerecord-import gem".I have the following Models

question.rb

require 'csv'class Question < ApplicationRecord    has_many :question_answers, dependent: :destroy    has_many :answers, through: :question_answers    belongs_to :category    belongs_to :product

answer.rb

class Answer < ApplicationRecord    has_many :question_answers, dependent: :destroy    has_many :questions, through: :question_answers end

question_answer.rb

class QuestionAnswer < ApplicationRecord    belongs_to :question    belongs_to :answerend

The below method is to handle the CSV data and prepare it to be saved using ActiveRecord import gem

def self.from_csv(file)        questions = []        CSV.foreach(file.path, headers: true) do |row|            category = Category.find_by(name: row['category'].strip)            product = Product.find_by(title: row['product'].strip)            parent_q = Question.find_by(qname: row['parent'])            question = Question.new(                question: row['question'],                qtype: row['qtype'],                tooltip: row['tooltip'],                parent: parent_q,                position: row['position'],                qname: row['qname'],                category_id: category.id,                product_id: product.id,                state_id: row['state_id'],                explanation: row['explanation']            )            answers = row['answers'].split(" | ") if row['answers'].present?            if answers.present?                answers.each do |a_str|                    answer_arr = a_str.split(',')                    question.answers.build(answer: answer_arr[0] || "", value: answer_arr[1] || "", pdf_parag: answer_arr[2] || "", key: answer_arr[3] || "", position: answer_arr[4] || "", note: answer_arr[5] || "")                end            end            p question.answers.inspect            questions << question        end        imported_obj = Question.import questions, recursive: true, validate: false    end

the code insert questions but without their answers, it gives an error saying:

NoMethodError (undefined method `answer_id=' for #<Answer:0x000000000>

I'm using Heroku

Update 1

CSV Sample

enter image description here

any help is highly appreciated


Viewing all articles
Browse latest Browse all 4616

Trending Articles