lundi 15 avril 2019

Send foreign key objects with all child or children objects

is there any way to always retrieve parent objects with the child or children object for a rails API only application ?

e.g. I have a @students array. Each student object in @students array has two foreign keys as standard_id and school_id. Now all the objects have by default standard_id and school_id. Instead I want standard object and school object in each student object in the @students array.

The response which I get

[
  {
    "id": 1,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:36:03.000Z",
    "updated_at": "2019-04-14T11:36:03.000Z"
  },
  {
    "id": 2,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:41:38.000Z",
    "updated_at": "2019-04-14T11:41:45.000Z"
  }
]

The response which I want

[
  {
    "id": 1,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:36:03.000Z",
    "updated_at": "2019-04-14T11:36:03.000Z",
    "standard": {
      "id": 1,
      "name": "1",
      "created_at": "2019-04-14T11:32:15.000Z",
      "updated_at": "2019-04-14T11:32:15.000Z"
    },
    "school": {
      "id": 1,
      "name": "SACS",
      "created_at": "2019-04-14T11:35:24.000Z",
      "updated_at": "2019-04-14T11:35:24.000Z"
    }
  },
  {
    "id": 2,
    "standard_id": 1,
    "school_id": 1,
    "created_at": "2019-04-14T11:41:38.000Z",
    "updated_at": "2019-04-14T11:41:45.000Z",
    "standard": {
      "id": 1,
      "name": "1",
      "created_at": "2019-04-14T11:32:15.000Z",
      "updated_at": "2019-04-14T11:32:15.000Z"
    },
    "school": {
      "id": 1,
      "name": "SACS",
      "created_at": "2019-04-14T11:35:24.000Z",
      "updated_at": "2019-04-14T11:35:24.000Z"
    }
  }
]

Is there any common solution for all controllers ? Because the application is already built. Its very hectic now to format data manually in every controller. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire