Jeffrey C Jeffrey C - 2 months ago 15
Ruby Question

Get associations when doing Get request

I am working on ruby on rails as my API with mongoid. Suppose I have 2 models:

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

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


I want to get all dogs that human has when I query all humans, how do I do this?

I know embedded documents can do this, but then I cannot find dog document easily. That is why I use association rather than embedded document.

Expected output when I query all human:

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


Thanks in advance. I am very new on this and sorry if I asked some stupid questions.

Answer
humans = Human.includes(:dog)

humans consists of the required data with each individual containing the dogs they own with details such as their name.