You can use the as_json
method directly on the result of your model, along with the parameters include
and except
; for example:
Family.first.as_json(include: :categories, except: :created_at, :updated_at)
Result:
{
id: 1
descripcion: 'Ejemplo',
categories: [
{ id: 1, descripcion: "category 1", created_at: "2018-01-01T00:00:00", updated_at: "2018-01-01T00:00:00" },
{ id: 2, descripcion: "category 2", created_at: "2018-01-01T00:00:00", updated_at: "2018-01-01T00:00:00" },
{ id: 3, descripcion: "category 3", created_at: "2018-01-01T00:00:00", updated_at: "2018-01-01T00:00:00" },
{ id: 4, descripcion: "category 4", created_at: "2018-01-01T00:00:00", updated_at: "2018-01-01T00:00:00" }
]
}
include
indicates the associations you want to include and except
indicate the columns to be omitted from the base object (i.e. Family
); with that result you could then read only the id
of each category, or, you could indicate that it only brings you the id
:
Family.first.as_json(include: [categories: { only: :id }], except: :created_at, :updated_at)
Result:
{
id: 1
descripcion: 'Ejemplo',
categories: [
{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }
]
}
This is the simplest form, however you could not generate the arrangement with the id
as you specify in your question; If you need that option, then I would recommend using jBuilder or ActiveModel Serializer .