I am using active_model_serializers
in my app (for API's):
class TrainingModuleSerializer < ActiveModel::Serializer
attributes :id, :name, :description, :status, :module_type
has_many :courses, serializer: CourseSerializer
end
class CourseSerializer < ActiveModel::Serializer
attributes :id, :name
end
def training_module_list
@training_modules = TrainingModule.where(tenant_id: 1)
render :json => @training_modules
end
In some API's, I need to add courses data (there is has_many
association with training_module
), but in some API's I don't want to add courses data.
Can anybody explain how I can do this?
Just create one more serializer without has_many
class SimpleTrainingModuleSerializer < ActiveModel::Serializer
attributes :id, :name, :description, :status, :module_type
end
and use it in the controller
render json: @record, serializer: SimpleTrainingModuleSerializer