Reputation: 1515
I got a problem with my Rails app. When I render a JSON, the nested attributes get repeated inside (like JSON example). Here is my API Controller, Serializer, both models and JSON response.
PS: After a lot of updates I get started with this issue, before that, it work fine. I don't know what was. My ruby version is ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
and my rails version is Rails 4.2.4
PS2: Sorry for my bad english
ingreso.rb
class Ingreso < ActiveRecord::Base
belongs_to :departamento, touch: true
belongs_to :concepto
[...]
end
departamento.rb
class Departamento < ActiveRecord::Base
has_many :ingresos
[...]
end
api/serializers/ingreso_controller.rb
class Api::V1::IngresosController < Api::V1::BaseController
include ActiveHashRelation
before_filter :authenticate_user!
def show_for_departamento
ingresos = Ingreso.where(departamento_id:params[:id]).order("id DESC")
render(
json: ActiveModel::ArraySerializer.new(
ingresos,
each_serializer: Api::V1::IngresoSerializer,
root: 'ingresos'
)
)
end
api/serializers/ingreso_serializer.rb
class Api::V1::IngresoSerializer < Api::V1::BaseSerializer
attributes :field1, :field2, :field3, :field4, :field5, :concepto, :colaborador, :departamento
def formapago
object.try(:formapago).try(:nombre) || "Sin información"
end
def colaborador
object.try(:colaborador).try(:full_name) || "Sin información"
end
def created_at
object.created_at.in_time_zone.iso8601 if object.created_at
end
def updated_at
object.updated_at.in_time_zone.iso8601 if object.created_at
end
JSON
{
"myRoot": [
{
"field1": 13201,
"field2": -5720,
"field3": null,
"field4": "2016-04-11T00:00:00.000-04:00",
"field5": "2016-04-10T00:00:00.000-04:00",
"concepto": {
"concepto": {
"data1": 1,
"data2": "Gasto Común",
"created_at": "2013-01-03T15:49:16.000-04:00",
"updated_at": "2015-02-05T15:54:12.363-04:00",
"data3": 1,
"data4": "gasto-comun",
"data5": false
}
},
"colaborador": "Sin información",
"departamento": {
"departamento": {
"another_field1": 101,
"another_field2": "1305",
"another_field3": 370,
"another_field4": 1,
"created_at": "2013-01-05T01:05:36.000-04:00",
"updated_at": "2016-05-20T11:48:30.892-04:00",
}
}
}
]
}
Upvotes: 0
Views: 601
Reputation: 1515
Ok, I got a solution. In my ingreso_serializer.rb
I define departamento
like this:
class Api::V1::IngresoSerializer < Api::V1::BaseSerializer
attributes :field1, :field2, :field3, :field4, :field5, :concepto, :colaborador, :departamento
def departamento
object.departamento.as_json(root: false, include: :propietario)
end
def concepto
object.concepto.as_json(root: false)
end
end
Upvotes: 0