尝试使用“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 样本
非常感谢任何帮助