我有模型anwer_pair.rb
class AnswerPair
include Mongoid::Document
embedded_in :question
embedded_in :survey
field :answer1, type: String
field :answer2, type: String
...
field :correct, type: Boolean, default: true
...
def new(answer1 = "answer1", answer2 = "answer2", correct = false)
@answer1 = answer1
@answer2 = answer2
@correct = correct
end
...
end
嵌套在question.rb
中class Question
include Mongoid::Document
...
field :name, type: String
...
embeds_many :answer_pairs
accepts_nested_attributes_for :answer_pairs, allow_destroy: true
...
end
使用表单将问题保存到数据库工作正常(我使用mongoid)。现在,我想在更新或创建问题之前为问题添加更多答案对。出于这个原因,我在"更新"中调用了以下方法。和"创造"在questions_controller.rb中
class QuestionsController < ApplicationController
...
def update
...
fill_up_answer_pairs(@question)
...
end
def create
...
fill_up_answer_pairs(@question)
...
end
...
def fill_up_answer_pairs(question)
if(question.answer_pairs.any?)
question.answer_pairs.where(correct: false) do |pair|
pair.delete
end
question.answer_pairs.where(correct: true) do |pair1|
question.answer_pairs.where(correct: true) do |pair2|
if(pair1.answer1 != pair2.answer1 && pair1.answer2 != pair2.answer2)
question.add_to_set(:answer_pairs, AnswerPair.new(pair1.answer1, pair2.answer2, false))
end
end
end
# having "question.update_attributes(question.answer_pairs)" here would cause a "NameError ... undefined method `keys' for #<Array ..."
end
end
但它不会保存添加的答案对。我究竟做错了什么? 任何帮助表示赞赏!
答案 0 :(得分:0)
以下更改修复了问题: 在where子句之后我忘了&#34;每个&#34; s我将answer_pair.rb的新方法更改为
def self.buildnew(answer1 = "answer1", answer2 = "answer2", correct = false)
ap = AnswerPair.new
ap.answer1 = answer1
ap.answer2 = answer2
ap.correct = correct
return ap
end
不需要使用question.update_attributes。