尝试使用初始化调用将文档推送到Mongoid的“embeds_many”集合时出现Ruby错误

时间:2013-11-26 23:28:31

标签: ruby-on-rails ruby rspec mongoid

我有一个可提交的课程,其中embeds_many提交。我有一个rspec测试,我想将一个新的Submission推送到Submittable.submissions集合。如果我使用哈希初始化提交它可以工作,但如果我使用初始化调用,它无法告诉我

  

NoMethodError:'

中未定义的方法[]' for nil:NilClass ./spec/models/submittable_spec.rb:14:in阻止(4级)

Submittable

class Submittable
  include Mongoid::Document

  belongs_to :course_booking
  embeds_many :submissions

  field :week, type: Integer
  field :topic_name, type: String
  field :date_due, type: Date
  field :date_submitted, type: Date

end

提交

class Submission
  include Mongoid::Document

  embedded_in :submittable

  field :date_submitted, type: Date
  field :normal_mistakes, type: Integer
  field :challenge_questions_attempted, type: Integer
  field :challenge_questions_mistakes, type: Integer

  def initialize(date_submitted, normal_mistakes)
    @date_submitted = date_submitted
    @normal_mistakes = normal_mistakes
  end

end

Submittable_spec

require 'spec_helper'

describe Submittable do

  context "submittable with submissions" do
    before {
      @submittable = Submittable.new
    }
    describe "one complete submission" do
      before {
        #WORKS (if Submission#initialise is removed)
        #@submittable.submissions << Submission.new(date_submitted: Date.today, normal_mistakes: 0)
        #DOES NOT WORK
        @submittable.submissions << Submission.new(Date.today, 0)
      }
      it "should be complete" do
        expect(@submittable.complete?).to eq(true)
      end
    end

我对ruby相当新,所以它可能是非常明显的,但为什么使用hash的初始化与使用initialise方法的行为不同?

我正在使用mongoid(3.1.5),ruby 2.0.0和rails(3.2.13)

干杯

1 个答案:

答案 0 :(得分:0)

Mongoid::Document#intialize需要一些参数(rdoc):

initialize(attrs = nil, options = nil)

您的实现会覆盖,这会导致Mongoid产生一些混乱。如果您要覆盖initialize,则需要接受这些参数并致电super。我建议避免它 - 这是你为这种不引人注目的API付出的代价之一。

最佳解决方案是单独留下initialize并使用您的第一种方法 - Submission.new(date_submitted: Date.today, normal_mistakes: 0)