I used AMS (0.8) with Rails 3.2.19, but one place where I really struggle with them is how to control whether serializers include their associations or not. I obviously use AMS to create the JSON API. Sometimes a serializer is a leaf or the farthest element, and sometimes a higher level, and must include associations. My question is the best way to do this or is it the solution that I am doing below the work (or is it the best solution).
I saw some of the discussions, but I find them very confusing (and version based). Is it clear that there are include_XXX for Serializer attributes or associations? a method for everyone, and you can return a true or false statement here.
Here my suggested code is a winemaker who has a lot of wines. So will you do it?
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 my 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
source share