将关联加载到一个级别,同时在活动模型序列化器中有条件地侧载关联

Load associations to one level while conditionally sideloading associations in Active model serializers

A​​MS 版本 0.8.3,

我创建了一个这样的 base_serializer.rb 并对其进行了扩展。

class BaseSerializer < ActiveModel::Serializer
  def include_associations!
    if @options[:embed]
      embed = @options[:embed].split(',').map{|item| item.strip.to_sym}
      embed.each do |assoc|
        include! assoc if _associations.keys.include?(assoc)
      end
    end
  end
end

class EventSerializer < BaseSerializer
  attributes :id, :name
  has_many :organizers, serializer: OrganizerSerializer
  has_many :participants, serializer: ParticipantSerializer
end

class OrganizerSerializer < BaseSerializer
  attributes :id, :name
  has_many :related, serializer: RelatedSerializer
end

class ParticipantSerializer < BaseSerializer
  attributes :id, :name
  has_many :related, serializer: RelatedSerializer
end

class RelatedSerializer < BaseSerializer
  attributes :id, :name
  has_many :something, serializer: SomethingSerializer
end

而EventsController中的index方法写成

# GET /events?embed=organizers,participants
  def index
      @events = Event.all
      render json: @events, embed: params[:embed]
  end

有了这个,我可以得到活动、组织者和参与者的 :id 和 :name。但是,我也想要相关关联的属性。我不需要序列化程序的详细信息。我想为每个协会达到这个级别。我怎样才能做到这一点?

我最终这样做是为了达到同样的目的。

class BaseSerializer < ActiveModel::Serializer
  def include_associations!
    @options[:embed_level] ||= 2
    return unless @options.key?(:embed) && @options[:embed_level] != 0
    embed = @options[:embed].split(',').map{|item| item.strip.to_sym}
    embed.each do |assoc|
      next unless _associations.key?(assoc)
      assoc_serializer = serializer_for(assoc)
      embed = @options[:embed]
      embed_level = @options[:embed_level]
      @options[:embed_level] = @options[:embed_level] - 1
      @options[:embed] = assoc_serializer._associations.keys.join(",")
      include! assoc
      @options[:embed_level] = embed_level
    end
  end

  def serializer_for(assoc)
    serializer = _associations[assoc].options[:serializer]
    return serializer if serializer
    assoc.to_s.classify.concat("Serializer").constantize
  end
end

参考:Github Issue Link 特别感谢 Yohan Robert!!!