Rails 4 个具有三个嵌套模型的 AMS

Rails 4 AMS with three nested models

我是第一次使用 active_model_serializers gem。我使用的版本是 0.10.2

我有三个模型具有这样的关联:

class Song < ActiveRecord::Base
    has_many :questions
end

class Question< ActiveRecord::Base
    belongs_to :song
    has_many :answers
end

class Answer< ActiveRecord::Base
    belongs_to :question
end

我生成了三个这样的序列化器:

class SongSerializer < ActiveModel::Serializer
   attributes :id, :audio, :image

   has_many :questions
end

class QuestionSerializer < ActiveModel::Serializer
   attributes :id, :text

   belongs_to :song
   has_many :answers
end

class AnswerSerializer < ActiveModel::Serializer
   attributes :id, :text

   belongs_to :question
end

但不幸的是,我的 json 回复没有显示问题的答案,但显示了歌曲和问题。

谷歌搜索后我尝试添加 ActiveModelSerializers.config.default_includes = '**' 或来自这样的文档:

 class Api::SongsController < ApplicationController
    def index
        songs = Song.all

        render json: songs, include: '**' #or with '*'
    end
 end

但这导致我出现堆栈级别太深的错误

那么我应该怎么做才能得到 json 看起来像这样的响应 -

  {
  "id": "1",
  "audio": "...",
  "image": "...",
  "questions": [
    {
      "id": "1",
      "text": ".....",
      "answers": [
        {
          "id": "1",
          "text": "...."
        },
        {
          "id": "2",
          "text": "..."
        }
      ]
    },
    {
      "id": "2",
      "text": "....."
    }
  ]
}

因为像我在模型中那样简单地添加关联对第三个关联没有帮助。

如有任何帮助,我们将不胜感激!

您可以在您的控制器中使用以下结构进行操作

    respond_with Song.all.as_json(
      only: [ :id, :audio, :image ],
      include: [
        {
          questions: {
            only: [:id, :text],
            include: {
              anwers: {
                only: [ :id, :text ]
              }
            }
          }
        }
      ]
    )

经过更多搜索,我终于找到了有效的解决方案。我必须将嵌套模型添加到我的控制器中。

class Api::SongsController < ApplicationController
    def index
        songs = Song.all

        render json: songs, include: ['questions', 'questions.answers']
    end
 end

而且效果非常好!