当我需要显示我的连接表中包含的信息时,我面临着这样的情况。例如:
# == Schema Information
#
# Table name: quality_inspections
#
# id, content
#
# =============================================================================
class QualityInspection
has_many :inspection_inspectors
has_many :inspector, through: :inspection_inspectors
end
# == Schema Information
#
# Table name: inspection_inspectors
#
# quality_inspection_id, inspector_id, inspection_date
#
# =============================================================================
class InspectionInspector
belongs_to :quality_inspection
belongs_to :user, foreign_key: :inspector_id
end然后,我想要以下json:
{
"quality_inspectors": [{
"id": 1,
"content": "foo",
"inspectors": [{
"id": 1, // which is the user's id
"first_name": "Bar",
"last_name": "FooFoo",
"inspection_date": "random date"
}]
}]
}目前,我在序列化程序中执行以下操作:
module Api::V1::QualityInspections
class InspectorSerializer < ActiveModel::Serializer
type :inspector
attributes :id, :first_name, :last_name, :inspection_date
def id
inspector.try(:public_send, __callee__)
end
def first_name
inspector.try(:public_send, __callee__)
end
def last_name
inspector.try(:public_send, __callee__)
end
private
def inspector
@inspector ||= object.inspector
end
end
end你有更好的解决方案吗?或者可能我没有在序列化程序上使用正确的方法?
无论如何,当我要在连接表上显示信息时,我真的被卡住了。奇怪的是,我在使用cerebris/jsonapi-resources时也遇到了同样的问题。
编辑:GH上的链接问题:https://github.com/rails-api/active_model_serializers/issues/1704
发布于 2018-07-25 18:40:14
我不认为你需要放入额外的方法,比如id,first_name,last_name。相反,可以在序列化程序中使用关联来获取前面提到的适当的JSON数据。
https://stackoverflow.com/questions/36807688
复制相似问题