Use ActiveModel::Serializers to include two parent json arrays

前端 未结 2 1936
误落风尘
误落风尘 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.

    0 讨论(0)
  • 2021-02-04 08:59

    I solved it by creating a class called Search that incorporates aspects of ActiveModel

    class Search
      include ActiveModel::Serialization
      include ActiveModel::SerializerSupport
    
      attr_accessor :facilities, :instructors
    
      def initialize(facilities, instructors)
        @facilities, @instructors = facilities, instructors
      end
    end
    

    Then I created a Searches controller (nothing interesting there) and a Search serializer.

    class SearchSerializer < ActiveModel::Serializer
      has_many :instructors, embed: :objects
      has_many :facilities, embed: :objects
    end
    

    This creates my desired json, although now it is wrapped in a search hash:

    {search: {
      #the stuff I wanted 
    }}
    
    0 讨论(0)
提交回复
热议问题