[英]ActiveModel::Serializer: Recommended way to use with join table (has_many through)
I'm facing a case when a need to display information contained in my join table. 我正面临一种需要显示我的联接表中包含的信息的情况。 For example:
例如:
# == 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
Then, I'd like to have the following json: 然后,我想拥有以下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"
}]
}]
}
For now, I'm doing the following in my serializer: 现在,我正在序列化器中执行以下操作:
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
Do you have any better solution ? 您有更好的解决方案吗? Or maybe I'm not using the right methods on my Serializer ?
还是我在序列化器上使用的方法不正确?
Anyway, I'm really stuck when it came to display information on a join table. 无论如何,当我在连接表上显示信息时,我真的很困惑。 Oddly, I'd the same issue when using cerebris/jsonapi-resources.
奇怪的是,当使用cerebris / jsonapi-resources时,我会遇到同样的问题。
EDIT: Linked issue on GH: https://github.com/rails-api/active_model_serializers/issues/1704 编辑:GH上的链接的问题: https : //github.com/rails-api/active_model_serializers/issues/1704
I don't think you need to put additional methods such as id, first_name, last_name. 我认为您不需要添加其他方法,例如id,first_name,last_name。 Instead, use association within your serializer to get the appropriate JSON data as mentioned afore.
而是使用序列化程序中的关联来获取相应的JSON数据,如前所述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.