Add to Collection

Adds an association between two records.

  1. 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:

  1. $.post('/employee/7/involvedInPurchases/47', function (purchases) {
  2. console.log(purchases);
  3. });

Using Angular:

  1. $http.post('/employee/7/involvedInPurchases/47')
  2. .then(function (purchases) {
  3. console.log(purchases);
  4. });

Using sails.io.js:

  1. io.socket.post('/employee/7/involvedInPurchases/47', function (purchases) {
  2. console.log(purchases);
  3. });

Using cURL:

  1. curl http://localhost:1337/employee/7/involvedInPurchases/47 -X "POST"

Should return “Dolly”, the primary record:

  1. {
  2. "involvedInPurchases": [
  3. {
  4. "amount": 10000,
  5. "createdAt": "2014-08-03T01:50:33.898Z",
  6. "updatedAt": "2014-08-03T01:51:08.227Z",
  7. "id": 47,
  8. "cashier": 7
  9. }
  10. ],
  11. "name": "Dolly",
  12. "createdAt": "2014-08-03T01:16:35.440Z",
  13. "updatedAt": "2014-08-03T01:51:41.567Z",
  14. "id": 7
  15. }

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 a Purchase model with association: cashier: {model: 'Employee'}. You’ll also need at least an empty PurchaseController and EmployeeController. You can quickly achieve this by running:

    1. $ sails new foo
    2. $ cd foo
    3. $ sails generate api purchase
    4. $ sails generate api employee

…then editing api/models/Purchase.js and api/models/Employee.js.