Rails Active Model Serializer - HAS_MANY 및 부모 레코드 액세스
-
20-12-2019 - |
문제
일부 모델이 다른 모델을 포함하는 Active Model Serializer를 사용하여 일부 레일 모델의 JSON 표현을 작성하려고합니다. 예를 들어, 이벤트 및 참석자, 이벤트 has_and_belongs_to_many 참석자가 있습니다.
class EventSerializer < ActiveModel::Serializer
attributes :name
has_many :attendees, serializer: AttendeeSerializer
end
class AttendeeSerializer < ActiveModel::Serializer
attributes :name
end
.
JSON이 { name: 'Event One', attendees: [{ name: 'Alice' }, { name: 'Bob' }] }
와 같은 것으로 나타납니다.
이제, 참석자가 이벤트에 대해 말한 것을 추가하고 싶습니다. comments_to 이벤트, sectems_to 참석자를 comments_to comments. 나는 이벤트의 직렬화 된 출력에 상기 의견을 포함하고 싶다. 그래서 그것은 { name: 'Event One', attendees: [{ name: 'Alice', comments: [{ text: 'Event One was great!'}] }, { name: 'Bob', comments: [] }] }
가 될 것이다.
나는 그것을 가질 수 있었다
class AttendeeSerializer < ActiveModel::Serializer
attributes :name
has_many :comments
end
.
그러나 그 모든 이벤트에 대해이 참석자 가이 모든 의견을 선택합니다. 나는 이것을 써주고 싶지만, 내가 직렬화를하고있는 특정 이벤트를 어떻게 찾을 수 있습니까? 어떻게 든 '부모'객체에 액세스 할 수 있습니까? 아니면 has_many serializer에 옵션을 전달할 수 있습니까?
class AttendeeSerializer < ActiveModel::Serializer
attributes :name
has_many :comments
def comments
object.comments.where(event_id: the_event_in_this_context.id)
end
end
.
이거 할 수있는 것이거나,이 특정 사용 사례를 위해 다른 방법으로 JSON을 빌드해야합니까?
해결책
Control을 얻기 위해 수동으로 일을 할 것입니다 :
class EventSerializer < ActiveModel::Serializer
attributes :name, :attendees
def attendees
object.attendees.map do |attendee|
AttendeeSerializer.new(attendee, scope: scope, root: false, event: object)
end
end
end
class AttendeeSerializer < ActiveModel::Serializer
attributes :name, :comments
def comments
object.comments.where(event_id: @options[:event].id).map do |comment|
CommentSerializer.new(comment, scope: scope, root: false)
end
end
end
.