Most of the questions on SO seems to be too outdated to solve this problem.
I want to serialize a model. Here's what my serializer looks like -
class AssignmentSerializer < ActiveModel::Serializer
belongs_to :lesson, class_name: "Lesson"
attributes :id, :student_id, :tutor, :name, :start_date, :end_date, :description, :lesson
end
This works perfectly well for situations where you want to serialize a single object in this form.
def index
if current_user&.student?
@assignments = Assignment.where(student_id: current_user.id)
@assignments_due = Assignment.find_due(current_user)
@submitted_assignments = Assignment.find_submitted(current_user)
elsif current_user&.tutor?
@assignments = Assignment.where(tutor_id: current_user.id)
end
respond_to do |format|
format.json { render json: @assignments }
end
end
But doesn't work when I want to serialize multiple objects like so:
def index
if current_user&.student?
@assignments = Assignment.where(student_id: current_user.id)
@assignments_due = Assignment.find_due(current_user)
@submitted_assignments = Assignment.find_submitted(current_user)
elsif current_user&.tutor?
@assignments = Assignment.where(tutor_id: current_user.id)
end
respond_to do |format|
format.json { render json: {
assignments: @assignments,
assignments_due: @assignments_due,
submitted_assignments: @submitted_assignments
}, each_serializer: AssignmentSerializer
}
end
end
I have tried multiple methods by following different methods I saw in this documentation but none seems to work.
Any idea what I could be doing wrong?
Update tried as suggested in answer and comment, but this approach did not work. Tried with and without the each_serializer key
respond_to do |format|
format.json { render json: {
assignments: @assignments.as_json,
assignments_due: @assignments_due.as_json,
submitted_assignments: @submitted_assignments.as_json
}, each_serializer: AssignmentSerializer
}
end