0

尝试使用“activerecord-import gem”将 CSV 文件导入数据库。我有以下型号

问题.rb

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

答案.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 :answer
end

以下方法是处理 CSV 数据并准备使用 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

代码插入问题但没有他们的答案,它给出了一个错误说:

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

我正在使用 Heroku

更新 1

CSV 样本

在此处输入图像描述

非常感谢任何帮助

4

1 回答 1

0

在不知道你的 csv 看起来的情况下,可能很难提供更多帮助,但错误可能来自以下行:

question.answers.build(answer: answer_arr[0], ...)

该行中的后一个属性可能没问题,(我假设value, pdf_parag, key,positionnote都是答案表上的列。如果不是这样,您可能会遇到更多问题。)但是您从answer: answer_arr[0].

它认为您正在尝试在记录上设置answer(or answer_id) 属性answer。假设answer_arr[0]是您要导入的数据的 id,您可以尝试answer: answer_arr[0]id: answer_arr[0].

但是,如果您正在导入数据,您可能需要考虑将 id 排除在导入之外,并让 rails 为您设置新的 id。一般来说,尝试覆盖框架管理主键的方式是一个坏主意。一旦你保存了你建立在问题上的答案,Rails 就会很聪明并且正确地设置你的外键。如果您绝对需要保留正在导入的数据中的 id,请考虑将它们放在新列中。

如果这不正确,请提供错误跟踪并提供一些来自 csv 的示例数据。

于 2019-07-19T16:34:41.707 回答