Mongoid with "Foreign Key"
As a veteran of mongodb, I have created the following structure:
User: {
name: str,
email: ...
}
Gift: {
# author and receiver refer to User objects obviously
author: object_id(...),
receiver: object_id(...),
name: str
...
}
And I would like to map this properly in mongoid:
class User
include Mongoid::Document
has_many :gifts
end
class Gift
include Mongoid::Document
belongs_to :user
end
However, the mapping is not correct. g = Gift.first; g.author is not defined. How do I do the referencing?
Technically, it's:
User <--- 1: N via author---> Gift 开发者_StackOverflow中文版<--- N:1 via receiver---> User
(meaning a user can be the author of many gifts, and a user can be the receiver of many gifts, BUT a gift can have only 1 author and receiver).
Plz help!!!
You'll probably have better luck with Rails if Gift looks like this:
Gift: {
# author and receiver refer to User objects obviously
author_id: object_id(...),
receiver_id: object_id(...),
name: str
...
}
And then, add a :foreign_key
to Gift:
class Gift
include Mongoid::Document
belongs_to :user, :foreign_key => 'author_id'
end
精彩评论