【问题标题】:Rails 4 AMS with three nested models具有三个嵌套模型的 Rails 4 AMS
【发布时间】:2016-08-21 20:49:30
【问题描述】:

我是第一次使用 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": "....."
    }
  ]
}

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

任何帮助将不胜感激!

【问题讨论】:

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


    【解决方案1】:

    最后经过一番搜索,我找到了可行的解决方案。我必须将嵌套模型添加到我的控制器中。

    class Api::SongsController < ApplicationController
        def index
            songs = Song.all
    
            render json: songs, include: ['questions', 'questions.answers']
        end
     end
    

    它就像一个魅力!

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 感谢您的回复。是的,我之前做过,但是这是自定义rails as_json方法,和AMS没有关系。我想了解有关 AMS 的更多信息。
      猜你喜欢
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多