我想让我的Test
类的实例在初始化时通过连接类得到五个练习问题。如果测试是“考试”,那么它无需参加课程即可获得5个考试问题。 (问题类型具有不同的模型)
到目前为止,它的行为不符合我的预期
self.practice_questions = []
它每次都会创建5个连接类,但是self.practice_questions数组保持为空。
def get_questions
puts "ASDASDASDASDSAD"
array = []
if self.for_practice
puts "ASDASDASOASKODKSAOKDASODKOASKDSAOKDOASKDOASK"
PracticeQuestion.sort_for_selection[0...5].each do |question|
array << question
question.use_practice_question
end
elsif for_practice === false
puts self.exam_questions
if self.exam_questions.length ===0
grab 5 unused exam type questions
ExamQuestion.unused[0...5].each do |question|
puts "grabbing question #{question.title}"
question.test = self
question.use_question
end
end
puts "hello"
puts self.practice_questions.length
self.practice_questions ||= array
self.save
puts self.practice_questions.length
self.practice_questions.each {|question| puts question.title}
end
答案 0 :(得分:0)
self.practice_questions ||= array
仅在self.practice_questions
为false或nil时分配数组,您确定它是其中之一吗?
如果practice_questions
是has_many,请尝试以下一项:
array.each do |el|
self.practice_questions << el
end
或:
self.practice_questions_ids = array.map(&:id)
https://guides.rubyonrails.org/association_basics.html#has-many-association-reference