我有以下MongoMapper模型:
class Album
include MongoMapper::Document
key :name, String
timestamps!
many :photos
end
class Photo
include MongoMapper::Document
key :caption, String
timestamps!
key :album_id, ObjectId
belongs_to :album
end
我正在创建相册和照片对象的实例,如下所示:
album = Album.create!(name: "NYE 2013")
photo = Photo.create!(caption: "Happy New Year!", album: album)
在此之后,当我执行photo.album == album
时,只要我没有重新加载照片对象,它就会返回true
。但是,只要我通过photo.reload
或稍后重新加载数据库中的照片对象,photo.album
就会返回nil
。
任何时候,album.photos
都会包含所说的照片对象,这让我感到困惑。
我有什么遗漏或做错了吗?像往常一样,感谢所有的帮助!
答案 0 :(得分:1)
确保您的环境设置正确且加载了正确的宝石......
我目前正在使用
gem 'mongo_mapper', :git => "git://github.com/mongomapper/mongomapper.git", :tag => "v0.13.0.beta2"
所以我启动了mmconsole
并在上面添加了你的类defs,然后执行了两个文档创建行。直接将它粘贴在......这一切都按预期工作:
2.0.0-p247 :016 > album = Album.create!(name: "NYE 2013")
=> #<Album _id: BSON::ObjectId('5321213766e76cf398000001'), created_at: 2014-03-13 03:08:39 UTC, name: "NYE 2013", updated_at: 2014-03-13 03:08:39 UTC>
2.0.0-p247 :017 > Album.count
=> 1
2.0.0-p247 :018 > photo = Photo.create!(caption: "Happy New Year!", album: album)
=> #<Photo _id: BSON::ObjectId('5321214966e76cf398000002'), album_id: BSON::ObjectId('5321213766e76cf398000001'), caption: "Happy New Year!", created_at: 2014-03-13 03:08:57 UTC, updated_at: 2014-03-13 03:08:57 UTC>
2.0.0-p247 :019 > Photo.count
=> 1
2.0.0-p247 :020 > photo.album.name
=> "NYE 2013"
2.0.0-p247 :021 > photo.inspect
=> "#<Photo _id: BSON::ObjectId('5321214966e76cf398000002'), album_id: BSON::ObjectId('5321213766e76cf398000001'), caption: \"Happy New Year!\", created_at: 2014-03-13 03:08:57 UTC, updated_at: 2014-03-13 03:08:57 UTC>"
2.0.0-p247 :022 > foto=Photo.first
=> #<Photo _id: BSON::ObjectId('5321214966e76cf398000002'), album_id: BSON::ObjectId('5321213766e76cf398000001'), caption: "Happy New Year!", created_at: 2014-03-13 03:08:57 UTC, updated_at: 2014-03-13 03:08:57 UTC>
2.0.0-p247 :023 > foto.album.name
=> "NYE 2013"
这应该可以帮助你调试......
这个较旧的github mongo_examples项目展示了一些实现关联的方法。