1

私はactive_model_serializers gemをはじめて使用しています。Rails 4 3つのネストされたモデルを持つAMS

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:私はこのような3つのシリアライザを生成した

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 

:私が使用しているバージョンは、私はこのような団体と三つのモデルを持っている0.10.2

です応答は私に質問の答えを示すものではありませんが、歌と質問が表示されています。

は、いくつかのグーグルでの後に私が追加しようとしました 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": "....." 
    } 
    ] 
} 

私がモデルでやっているようなアトリオンは、第3の協会のために助けにはならない。

助けていただけたら幸いです!

答えて

0

あなたは、私が働いて解決策を見つけたいくつかのより多くの検索後だから、最終的には、以下の構造

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

ありがとうございます。はい、私は前にやったことがありますが、これはカスタムレールas_jsonメソッドです、AMSとは関係ありません。私はAMSについてもっと学びたがっていました。 – Santar

1

であなたのコントローラでそれを行うことができます。私はコントローラにネストされたモデルを含むインクルードを追加しなければならなかった。

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

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

これは魅力的でした。

関連する問題