How to conditionally enable associations in Rial Active Serializer v0.8

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 
+6
source share
1 answer

I ran into this problem myself, and this is the cleanest solution so far (but I'm not a fan of this).

This method allows you to do things like:

/parents/1?include_children=true

or using cleaner syntax, for example:

/parents/1?include=[children] etc.

 # app/controllers/application_controller.rb class ApplicationController # Override scope for 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 is in this method is accessible in the serializer classes. # Pass in params for 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 

A kind of hacking for me, but it works. Hope you find this helpful!

+1
source

Source: https://habr.com/ru/post/978970/


All Articles