Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveModelSerializers in rails

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?

like image 761
code_aks Avatar asked Nov 30 '25 02:11

code_aks


1 Answers

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
like image 175
Vasilisa Avatar answered Dec 02 '25 15:12

Vasilisa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!