我正在使用mongomapper,我使用以下方法保存关联:
class Task
include MongoMapper::Document
key :user_id, ObjectId #also works without this line
belongs_to :user
def self.add(user)
a = self.new
a.user_id = user
a.save
end
在用户模型中,我添加了:很多:任务
现在,我想保存两个用户(在html表单中我从Users集合中选择2个用户),而不使用数组,我想单独保存它们:
class Task
include MongoMapper::Document
key :from_user_id, ObjectId # user1 links to the Users model
key :to_user_id, ObjectId # user2 links to the Users model
我怎么做到这一点?
答案 0 :(得分:1)
在指定键和类名时,MongoMapper与ActiveRecord具有类似的选项。你可以这样做:
class Task
include MongoMapper::Document
key :to_user_id, ObjectId
key :from_user_id, ObjectId
belongs_to :from_user, class_name: 'User', foreign_key: :from_user_id
belongs_to :to_user, class_name: 'User', foreign_key: :to_user_id
end