0
AMS版本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索引方法寫成
# GET /events?embed=organizers,participants
def index
@events = Event.all
render json: @events, embed: params[:embed]
end
有了這個,我可以得到:ID和:事件,組織者和參與者的名字。但是,我也需要相關聯繫的屬性。我不需要串行器的細節。我想爲每個協會去這個級別。我怎樣才能做到這一點?