Use ActiveModel::Serializers to include two parent json arrays

前端 未结 2 1968
误落风尘
误落风尘 2021-02-04 08:43

I\'m trying to send my front-end application json that looks like this:

{
  facilities: [
     {id: 5, name: \'happy days ranch\', location: { address: \'1424 Pa         


        
2条回答
  •  轮回少年
    2021-02-04 08:44

    This is my solution:

    render json: {
      facilities: ActiveModel::ArraySerializer.new(@facilities, each_serializer: FacilitySerializer, root: false),
      instructors: ActiveModel::ArraySerializer.new(@instructors, each_serializer: InstructorSerializer, root: false)
    }
    

    It's a little bit dirty. It basically instantiates what would be instantiated except done manually and twice. Both result sets are rendered using ActiveModel::Serializers in the correct format.

提交回复
热议问题