Object有很多对象在active_model_serializers中有很多对象

时间:2015-07-21 10:45:35

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

在这两天的时间里,我把头靠在墙上,弄清楚如何显示对象有很多对象在active_model_serializers中有很多对象。这是我的序列化器:

部分序列化程序:

class SectionSerializer < ActiveModel::Serializer
   attributes :id, :title, :description

   has_many :questions, foreign_key: 'section_id', class_name: 'Comment'
end

以下是我的评论序列化程序

class CommentSerializer < ActiveModel::Serializer
  attributes :id, :body

  belongs_to :section

  has_many :replies, class_name: 'Comment', foreign_key: 'question_id'
  belongs_to :question, class_name: 'Comment'
end

基本上我想实现部分 has_many 问题问题 has_many 回复,但两者都问题回复是同一型号,评论型号。

问题是当我获取所有部分时如何包含回复。现在我得到了这个JSON:

  {
     "id": 1,
     "title": "section 1",
     "description": "Lorem ipsum dolor sit amet",
     "questions": [
         {
            "id": 1,
            "body": "question 1"
         }
      ]
   }

正如我们所看到的,在问题数组中没有回复,我需要JSON类似于序列化程序。

   {
     "id": 1,
     "title": "section 1",
     "description": "Lorem ipsum dolor sit amet",
     "questions": [
         {
            "id": 1,
            "body": "question 1",
            "replies" : [
                {
                   "id": 2,
                   "body": "reply 1 for question 1"
                },
                {
                   "id": 3,
                   "body": "reply 2 for question 1"
                }
            ]
         }
      ]
   }

我非常感谢你的帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以指定要用于嵌套资源的序列化程序。序列化程序可以应用于任何模型。您必须注意将正确的序列化程序应用于控制器中的正确对象,这就是全部。

class SectionSerializer < ActiveModel::Serializer
   attributes :id, :title, :description
   has_many :questions, foreign_key: 'section_id', class_name: 'Comment', serializer: CommentSerializer, embed: :object
end

class QuestionSerializer < ActiveModel::Serializer
  attributes :id, :body
  has_many :replies, ..., embed: :object, serializer: ReplySerializer
end

class ReplySerializer < ActiveModel::Serializer
  attributes :id, :body
end
相关问题