Rails Active Model Serializer - has_many and accessing the parent record

前端 未结 1 1230
温柔的废话
温柔的废话 2021-01-31 11:04

I\'m trying to build a JSON representation of some Rails models using Active Model Serializer, where some models embed others. For example, I have Event and Attendees, Event has

1条回答
  •  别那么骄傲
    2021-01-31 11:23

    I'd do things manually to get 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
    

    0 讨论(0)
提交回复
热议问题