Reputation: 870
I have the following MongoMapper models:
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
I am creating instances of the album and photo object as follows:
album = Album.create!(name: "NYE 2013")
photo = Photo.create!(caption: "Happy New Year!", album: album)
After this, when I execute photo.album == album
it returns true
as long as I haven't reloaded the photo object. However, as soon as I reload the photo object from the database by doing either photo.reload
or at a later time, photo.album
returns nil
.
At all times, album.photos
does include the said photo object, which is confusing me.
Is there something I am missing or doing wrong? As usual, thanks for all the help!
Upvotes: 1
Views: 118
Reputation: 3235
Make sure you have your environment set up right and the proper gems loaded...
I am currently using
gem 'mongo_mapper', :git => "git://github.com/mongomapper/mongomapper.git", :tag => "v0.13.0.beta2"
So I fired up mmconsole
and added your class defs above, and then executed your two document creation lines. Literally cut-n-paste it in... It all worked as expected:
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"
This should help you debug...
This older github mongo_examples project shows a handful of ways to implement associations.
Upvotes: 1