我的Rails应用程序出了问题。 当我渲染JSON时,嵌套属性会在内部重复(如JSON示例)。 这是我的API控制器,Serializer,模型和JSON响应。
PS:经过大量更新后我开始解决这个问题,在此之前,它运行正常。我不知道是什么。我的ruby版本为ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
,我的rails版本为Rails 4.2.4
PS2:抱歉我的英文不好
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 /串行化器/ 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 /串行化器/ 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",
}
}
}
]
}
答案 0 :(得分:0)
好的,我有一个解决方案。在我的ingreso_serializer.rb
我定义departamento
,如下所示:
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