【问题标题】:How do I create two relations in one document如何在一个文档中创建两个关系
【发布时间】:2014-07-12 23:28:18
【问题描述】:

我正在使用 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

我是怎么做到的?

【问题讨论】:

    标签: ruby mongodb associations mongodb-query mongomapper


    【解决方案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
    

    【讨论】:

    • 这创建了 String 而不是 ObjectId。当我用 result.to_user_id.name 调用结果时,我得到: undefined method `name' for "53c2be9456c02c3c90000001":String
    • 在定义密钥时尝试指定ObjectId 类型。见编辑。
    • 添加,调用时: puts a.to_user_id.name 我得到未定义的方法 `name' for BSON::ObjectId('53c2beda56c02c3cad000001'):BSON::ObjectId
    • 嗯,是的,因为to_user_idObjectId。你的意思是a.to_user.name
    • 呃!愚蠢的我:) 谢谢!所以现在可能是我问题的第二部分:) stackoverflow.com/questions/24724393/…
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 2019-02-28
    相关资源
    最近更新 更多