관련 모델이 두 개 있는데, parent= Activity
이며 비용과 관련이 있습니다. API 호출을 사용하여 serializer를 사용하는 작업 세부 정보를 가져오고 Serialize 된 Cost도 추가하려고합니다. 그래서 ActivitySerializer 내부에 나는이 시도했다 :활성 모델 시리얼 화기 has_many 연관이 작동하지 않습니다.
Class ActivitySerializer: < ActiveModel::Serializer
ActiveModel::Serializer.config.key_transform = :unaltered
attributes :id,
:name,
:description
...
has_many costs, each_serializer: CostSerializer
end
:
class CostSerializer < ActiveModel::Serializer
ActiveModel::Serializer.config.key_transform = :unaltered
attributes :id,
:amount,
:description
end
결과는 그 활동 자료가 좋아 보인다되지만 비용 데이터가 저에게이 제공 :
relationships":{"costs":{"data":[{"id":"20","type":"costs"}]}
을
양과 설명이 왜 떨어 졌는지 확실하지 않습니다. 내가 이렇게 할 경우, 그것은 (ActivitySerializer의 속성에 listCosts 추가) 작동 : 관계가없는,
def listCosts
object.costs.map do |cost|
CostSerializer.new(cost, scope:scope, root: false, event: object)
end
end
출력은 약간 다르지만 시리얼을 가지고 내가 원하는 속성. AMS 0.10에서 Rails 5.1.3을 사용하고 있습니다.
의 토론을 체크 아웃 할 수 있습니다. 추가 한 링크는 나를 이해하는 데 도움이됩니다. 고맙습니다. –