我有一個應用程序,您可以在其中下載測驗。每個測驗都有多個問題。每個問題有五個可能的答案。這是我的模型:Rails API從嵌套值返回嵌套值
首先測驗型號:
class Quiz < ApplicationRecord
has_many :questions
has_many :games
validates_presence_of :title
validates_presence_of :abstract
validates_presence_of :category_id
validates_uniqueness_of :title
end
的問題型號:(每題屬於競猜對象)
class Question < ApplicationRecord
belongs_to :quiz
has_many :answers
has_many :game_questions
validates_presence_of :quiz_id
validates_presence_of :question
end
最後是回答型號:(每個答案都屬於一個問題)
class Answer < ApplicationRecord
belongs_to :question
has_many :game_questions
validates_presence_of :question_id
validates_presence_of :answer
validates_inclusion_of :correct_answer, :in => [true, false]
validates_presence_of :order
end
我想通過這條路線做一個GET請求我QuizzesController /quiz_content /:ID,然後成爲測驗與相應的ID和所有問題,併爲每個問題所有連接的答案
我已經設法返回它的所有的答案了白卷:
def quiz_content
quiz_records = Quiz.where('id = ?', params[:id]).includes(:questions)
@quiz_records_with_associations = quiz_records.map do |record|
record.attributes.merge('questions' => record.questions)
end
render json: @quiz_records_with_associations
end
調用此控制器返回以下JSON網絡le:
[
{
"id": 1,
"title": "Testquiz",
"abstract": "Questions for dummies",
"category_id": 1,
"download": 0,
"created_at": "2017-05-20T17:16:42.511Z",
"updated_at": "2017-05-20T17:16:42.511Z",
"questions": [
{
"id": 1,
"quiz_id": 1,
"question": "What is 5 + 5?",
"created_at": "2017-05-20T17:16:42.561Z",
"updated_at": "2017-05-20T17:16:42.561Z"
},
{
"id": 2,
"quiz_id": 1,
"question": "What's the color of the sky?",
"created_at": "2017-05-20T17:16:42.588Z",
"updated_at": "2017-05-20T17:16:42.588Z"
},
{
"id": 3,
"quiz_id": 1,
"question": "How fast can a cheetah run?",
"created_at": "2017-05-20T17:16:42.602Z",
"updated_at": "2017-05-20T17:16:42.602Z"
},
{
"id": 4,
"quiz_id": 1,
"question": "How many eyes does a pig have?",
"created_at": "2017-05-20T17:16:42.620Z",
"updated_at": "2017-05-20T17:16:42.620Z"
},
{
"id": 5,
"quiz_id": 1,
"question": "How would you rate this quiz?",
"created_at": "2017-05-20T17:16:42.611Z",
"updated_at": "2017-05-20T17:16:42.611Z"
}
]
}
]
我現在的問題是,我無法弄清楚如何返回每個問題的所有五個答案。我希望你能幫助我。 :)
不工作時,得到folllowing錯誤: 未定義的方法'包括爲#<測驗:0x00000002074980> 提取的源(圍繞線#43): @quiz = Quiz.find(PARAMS [: id])。includes(questions::answers) – mfaorlkzus
檢查更新的答案。您需要更改find'的'順序和'includes' –
它的工作原理,但我只得到競猜資源...服務器日誌顯示下列數據庫查詢: 處理由QuizzesController#quiz_content爲HTML 參數:{ 「id」=>「1」} 測驗載入(0.1ms)選擇「測驗」。*從「測驗」WHERE(id ='1') 問題載入(0.2ms) 「WHERE」questions「。」「quiz_id」= 1 Answer Load(0.3ms)SELECT「answers」。* FROM「answers」WHERE「answers」。「question_id」IN(1,2,3,4,5) – mfaorlkzus