how to conditionally include associations in a Rails Active Model Serializer v0.8 -
i have used ams (0.8) rails 3.2.19 1 place struggle them how control whether serializers include associations or not. use ams build json api's. serializer leaf or furthest out element , it's top level , needs include associations. question best way or solution below work (or best solution).
i have seen of discussions find them confusing (and version based). it's clear serializer attributes or associations, there an include_xxx? method each , can return either truthy or falsey statement here.
here's proposed code - it's winemaker has many wine_items. how this?
model classes:
class wineitem < activerecord::base attr_accessible :name, :winemaker_id belongs_to :winemaker end class winemaker < activerecord::base attr_accessible :name has_many :wine_items attr_accessor :show_items end
serializers:
class winemakerserializer < activemodel::serializer attributes :id, :name has_many :wine_items def include_wine_items? object.show_items end end class wineitemserializer < activemodel::serializer attributes :id, :name end
and in controller:
class apiwinemakerscontroller < applicationcontroller def index @winemakers=winemaker.all @winemakers.each { |wm| wm.show_items=true } render json: @winemakers, each_serializer: winemakerserializer, root: "data" end end
i ran issue myself , cleanest solution far (but i'm not fan of it).
this method allows things like:
/parents/1?include_children=true
or using cleaner syntax like:
/parents/1?include=[children]
, etc...
# app/controllers/application_controller.rb class applicationcontroller # override scope activemodel-serializer (method defined below) # see: https://github.com/rails-api/active_model_serializers/tree/0-8-stable#customizing-scope serialization_scope(:serializer_scope) private # whatever in method accessible in serializer classes. # pass in params conditional includes. def serializer_scope openstruct.new(params: params, current_user: current_user) end end # app/serializers/parent_serializer.rb class parentserializer < activemodel::serializer has_many :children def include_children? params[:include_children] == true # or if using other syntax: # params[:includes].include?("children") end end
kinda hackish me, works. hope find useful!
Comments
Post a Comment