RoR,mongoid:BSON无法在更新时序列化对象

时间:2014-12-14 17:32:40

标签: ruby-on-rails mongoid bson

我有模型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 self.buildnew(answer1 = "answer1", answer2 = "answer2", correct = false)
    ap = AnswerPair.new
    ap.answer1 = answer1
    ap.answer2 = answer2
    ap.correct = correct
    return ap
  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
  before_save :fill_up_answer_pairs
  ...
  def delete_all_false_answer_pairs
    if(self.answer_pairs.any?)
      self.answer_pairs.where(correct: false).each do |pair|
        pair.delete
      end
    end
  end

  def fill_up_answer_pairs
    if(self.answer_pairs.any?)
      self.answer_pairs.where(correct: true).each do |pair1|
        self.answer_pairs.where(correct: true).each do |pair2|
          if(pair1.answer1 != pair2.answer1)
            if(pair1.answer2 != pair2.answer2) 
              self.add_to_set(:answer_pairs, AnswerPair.buildnew(pair1.answer1, pair2.answer2, false)) 
            end
          end
        end
      end
    end
  end
end

使用表单创建问题工作正常(我使用mongoid)。用户无法选择答案对是否正确。默认情况下它是正确的,就像你在上面看到的那样。错误的答案对由" before_save:fill_up_answer_pairs"自动添加。现在出现了问题。为了编辑问题,我删除了所有错误的答案对,如此

class QuestionsController < ApplicationController
     ...
     def edit
       @question.delete_all_false_answer_pairs
     end
end

再次使用表格。到目前为止,这么好,但是当我提交表单并且它来到&#34; before_save:fill_up_answer_pairs&#34;时,我收到错误

BSON::InvalidDocument at /questions/548dc31288a49401b50000c2
Cannot serialize an object of class AnswerPair into BSON.

at the line&#34; self.add_to_set ...&#34;。有人可以告诉我,为什么它适用于create方法但不适用于edit方法?我究竟做错了什么?任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

添加

after_save :fill_up_answer_pairs

到您的问题模型并更改

self.add_to_set(:answer_pairs, AnswerPair.buildnew(pair1.answer1, pair2.answer2, false)) 

self.answer_pairs.create(:answer1 => pair1.answer1, :answer2 => pair2.answer2, :correct => false)

然后它应该工作