1

我第一次使用active_model_serializers gem。我使用的版本是0.10.2Rails 4具有三個嵌套模型的AMS

我有三個型號,聯想這樣的:

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 

我產生3個串行這樣的:

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": "....." 
    } 
    ] 
} 

因爲只需添加associ像我會在模特中做的事情對第三個協會沒有幫助。

任何幫助,將不勝感激!

回答

0

您可以用下面的結構做它在你的控制器

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

謝謝你的迴應。是的,我之前做過,但這是自定義rails as_json方法,它與AMS無關。我想了解更多關於AMS的信息。 – Santar

1

所以最後經過一番搜索,我發現解決方案,它的工作。我必須添加到我的控制器包含嵌套模型。

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

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

它就像一個魅力!