作为mongodb的资深人士,我创建了以下结构:
User: {
name: str,
email: ...
}
Gift: {
# author and receiver refer to User objects obviously
author: object_id(...),
receiver: object_id(...),
name: str
...
}
我想在mongoid中正确映射这个:
class User
include Mongoid::Document
has_many :gifts
end
class Gift
include Mongoid::Document
belongs_to :user
end
但是,映射不正确。 g = Gift.first; g.author未定义。我该如何进行参考?
从技术上讲,它是:
User <--- 1: N via author---> Gift <--- N:1 via receiver---> User
(意味着用户可以是许多礼物的作者,用户可以是许多礼物的接收者,但礼物只能有1位作者和接收者)。
Plz帮助!!!
答案 0 :(得分:6)
如果Gift看起来像这样,你可能会有更好的运气:
Gift: {
# author and receiver refer to User objects obviously
author_id: object_id(...),
receiver_id: object_id(...),
name: str
...
}
然后,在礼物中添加:foreign_key
:
class Gift
include Mongoid::Document
belongs_to :user, :foreign_key => 'author_id'
end