使用嵌入式文档数组创建对象时出错

时间:2012-07-01 14:31:20

标签: ruby mongodb mongomapper

这是我创建的代码脚本,用于使用MongoMapper

测试我的对象模型架构
require 'rubygems'
require 'mongo_mapper'

class Voter
    include MongoMapper::Document

    key :name, String , required: true

    belongs_to :vote
    belongs_to :event
end

class Place
    include MongoMapper::Document

    key :name, String, required: true

    belongs_to :event
    belongs_to :vote
end

class Event
    include MongoMapper::Document

    key :name, String, required: true
    key :description, String

    one :voter
    many :places
    many :votes
end

class Vote
    include MongoMapper::EmbeddedDocument

    one :voter
    one :place
end

voters = 
[
    Voter.new({name: "Daniel P"}),
    Voter.new({name: "Garage"}),
    Voter.new({name: "John"}),
    Voter.new({name: "Smith"})
];

places = 
[
    Place.new({name: "Scruby's"}),
    Place.new({name: "Korean BBQ"}),
    Place.new({name: "Waffle House"})
];

event = Event.create(
{
    name: "BBQ Friday",
    description: "Let's eat good BBQ!",
    voter: voters[0],
    places: [places[0], places[1]],
    votes:
    [
        Vote.new(voter: voters[0], place: places[1]), #fails here
        Vote.new(voter: voters[1], place: places[0]),
        Vote.new(voter: voters[2], place: places[0])
    ]
});


MongoMapper.connection = Mongo::Connection.new('localhost')
MongoMapper.database = 'test'
Person.create({name: "Daniel"}).save;

voters[0].save

我得到的错误是/gems/mongo_mapper-0.11.1/lib/mongo_mapper/plugins/persistence.rb:49:in collection': undefined method collection'为nil:NilClass(NoMethodError)

我是否错误地定义了嵌入式文档?

0 个答案:

没有答案