Reputation: 893
I noticed I was not getting the same response on a post as I was on a get. Specifically, associations.
Referencing 'Create new record while associating w/ another new record' https://github.com/balderdashy/sails-docs/blob/master/reference/blueprint-api/Create.md
I recreate the scenario from the documentation with sails new testProj
, then sails generate api pony
and sails generate api pet
, then update the models to have a one-to-one association.
Pony
module.exports = {
attributes: {
pet: {
model: 'pet'
}
}
};
Pony
module.exports = {
attributes: {
pet: {
model: 'pet'
}
}
};
Pet
module.exports = {
attributes: {
pony: {
model: 'pony'
}
}
};
Then, sails lift
away.
POST /pony
JSON Req
{
"name": "Pinkie Pie",
"hobby": "ice skating",
"pet": {
"name": "Gummy",
"species": "crocodile"
}
}
JSON Res
{
"name": "Pinkie Pie",
"hobby": "ice skating",
"pet": 1,
"createdAt": "2014-11-21T19:18:09.161Z",
"updatedAt": "2014-11-21T19:18:09.161Z",
"id": 1
}
As you can see, the res
ponse did not include the full pet object, just its id. In the documentation, it shows the full object being returned.
The entries and the association were definitely created successfully,
GET - /pony/1
{
"pet": {
"name": "Gummy",
"species": "crocodile",
"createdAt": "2014-11-21T19:18:09.157Z",
"updatedAt": "2014-11-21T19:18:09.157Z",
"id": 1
},
"name": "Pinkie Pie",
"hobby": "ice skating",
"createdAt": "2014-11-21T19:18:09.161Z",
"updatedAt": "2014-11-21T19:18:09.161Z",
"id": 1
}
Is this an error in documentation, or an error in code? Either way, is there a way we can specify that we want the associations to be returned?
One-to-one associations are just showing up as the linked id, many to many do not show up at all. I was looking into the toObject()
function for waterline
for another issue when I saw the showJoins
option; it looks like it might be related to that.
In addition, this one-to-one association is actually only being created as a one-way association.
After completing the same as above:
GET - /pet/1
{
"name": "Gummy",
"species": "crocodile",
"createdAt": "2014-12-03T20:50:31.346Z",
"updatedAt": "2014-12-03T20:50:31.346Z",
"id": 1
}
Notice that no pony is returned.
Just to make sure...
GET - /pony/1/pet
{
"name": "Gummy",
"species": "crocodile",
"createdAt": "2014-12-03T20:50:31.346Z",
"updatedAt": "2014-12-03T20:50:31.346Z",
"id": 1
}
GET - /pet/1/pony
Res
Specified record (1) is missing relation 'pony'
Pony has a pet, pet has no pony.
Anything I'm doing wrong?
Upvotes: 1
Views: 2034
Reputation: 1762
You need to provide a via
attribute while defining two-way relations, otherwise they're assumed to be unrelated one-way joins.
Pony
module.exports = {
attributes: {
pet: {
model: 'pet',
via: 'pony'
}
}
};
Pet
module.exports = {
attributes: {
pony: {
model: 'pony',
via: 'pet'
}
}
};
It's mentioned in the docs for only in many-many
and one-many
relations, which might be an error.
Upvotes: 0