活动模型序列化器-使用多个键和值序列化模型

时间:2018-09-02 09:28:42

标签: ruby-on-rails active-model-serializers

关于SO的大多数问题似乎太过时而无法解决此问题。

我想序列化一个模型。 这是我的序列化器的样子-

class AssignmentSerializer < ActiveModel::Serializer
  belongs_to :lesson, class_name: "Lesson"
  attributes :id, :student_id, :tutor, :name, :start_date, :end_date, :description, :lesson
end

这非常适合您要序列化此对象形式的情况。

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

但是当我想序列化多个对象时不起作用:

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

我通过遵循在此documentation中看到的不同方法尝试了多种方法,但似乎没有一个起作用。

知道我可能做错了什么吗?

Update尝试按照答案和评论的建议进行尝试,但是这种方法不起作用。尝试使用和不使用each_serializer键

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

2 个答案:

答案 0 :(得分:3)

显然,答案一直就在那里,这有点令人困惑。 在我分享的同一个链接中,我找到了答案。 This link

这就是我使用ActiveModelSerializers::SerializableResource.new

的方法
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: ActiveModelSerializers::SerializableResource.new(@assignments),
            assignments_due: ActiveModelSerializers::SerializableResource.new(@assignments_due),
            submitted_assignments: ActiveModelSerializers::SerializableResource.new(@submitted_assignments)
            }
        }
    end
end

这给了我想要的确切结构。

答案 1 :(得分:0)

按照:https://github.com/rails/rails/blob/master/activemodel/lib/active_model/serializers/json.rb#L89

@assignments.as_json应该根据需要使用assignments序列化AssignmentSerializer