Add to Collection
Adds an association between two records.
POST /:model/:record/:association/:record_to_add?
This action pushes a reference to some other record (the "foreign" record) onto a collection attribute of this record (the "primary" record).
- If
:record_to_add
of an existing record is supplied, it will be associated with the primary record. - If no
:record_to_add
is supplied, and the body of the POST contains values for a new record, that record will be created and associated with the primary record. - If the collection within the primary record already contains a reference to the foreign record, this action will be ignored.
- If the association is 2-way (i.e. reflexive, with "via" on both sides) the association on the foreign record will also be updated.
Example
Add purchase 47 to the list of purchases that Dolly (employee #7) has been involved in.
Using jQuery:
$.post('/employee/7/involvedInPurchases/47', function (purchases) {
console.log(purchases);
});
Using Angular:
$http.post('/employee/7/involvedInPurchases/47')
.then(function (purchases) {
console.log(purchases);
});
Using sails.io.js:
io.socket.post('/employee/7/involvedInPurchases/47', function (purchases) {
console.log(purchases);
});
Using cURL:
curl http://localhost:1337/employee/7/involvedInPurchases/47 -X "POST"
Should return "Dolly", the primary record:
{
"involvedInPurchases": [
{
"amount": 10000,
"createdAt": "2014-08-03T01:50:33.898Z",
"updatedAt": "2014-08-03T01:51:08.227Z",
"id": 47,
"cashier": 7
}
],
"name": "Dolly",
"createdAt": "2014-08-03T01:16:35.440Z",
"updatedAt": "2014-08-03T01:51:41.567Z",
"id": 7
}
Notes
- This action is for dealing with plural ("collection") associations. If you want to set or unset a singular ("model") association, just use update.
The example above assumes "rest" blueprints are enabled, and that your project contains at least an 'Employee' model with association:
involvedInPurchases: {collection: 'Purchase', via: 'cashier'}
as well as aPurchase
model with association:cashier: {model: 'Employee'}
. You'll also need at least an emptyPurchaseController
andEmployeeController
. You can quickly achieve this by running:$ sails new foo $ cd foo $ sails generate api purchase $ sails generate api employee
...then editing
api/models/Purchase.js
andapi/models/Employee.js
.