在做 Get 请求时获取关联

Get associations when doing Get request

我正在 ruby rails 作为我的 API 和 mongoid。假设我有 2 个模型:

class Human
  field: salary, type: Integer
  has_many: dogs
end

class Dog
  field: name, type: String
  belongs_to: human
end

我想在查询所有人类时得到人类拥有的所有狗,我该怎么做?

我知道嵌入式文档可以做到这一点,但是我无法轻易找到狗文档。这就是为什么我使用关联而不是嵌入文档的原因。

我查询全人类时的预期输出:

[
    {
        "_id": "1",
        "salary": 5000,
        "dogs": [
            {
                "_id": "1",
                "name": "dog1",
            }
        ]
    },
    {
        "_id": "2",
        "salary": 8000,
        "dogs": [
            {
                "_id": "2",
                "name": "dog2",
            },
            {
                "_id": "3",
                "name": "dog3",
            }
        ]
    }
]

提前致谢。我对此很陌生,如果我问了一些愚蠢的问题,我很抱歉。

humans = Human.includes(:dog)

humans 包含所需的数据,每个人都包含他们拥有的狗以及他们的名字等详细信息。