【问题标题】:Object has many objects has many objects in active_model_serializers对象有很多对象 在 active_model_serializers 中有很多对象
【发布时间】:2015-07-21 10:45:35
【问题描述】:

这两天把我的头撞在墙上以弄清楚如何显示对象有很多对象在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

基本上我想实现Section has_many questionsQuestion has_many replies,但两者都 QuestionReply是同一个模型,即Comment模型。

问题是当我获取所有部分时如何包含回复。现在我得到了这个 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"
                }
            ]
         }
      ]
   }

非常感谢您的帮助。

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-22
      • 2012-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      相关资源
      最近更新 更多