【发布时间】:2017-05-25 12:00:32
【问题描述】:
我有一个应用程序,您可以在其中下载测验。每个测验都有多个问题。每个问题有五个可能的答案。这些是我的模型:
首先是测验模型:
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
我想通过这条路线/quiz_content/:id向我的QuizzesController发出一个get请求,然后成为具有相应id和所有问题的quiz 以及每个问题的所有相关答案
我已经设法返回一个包含所有答案的测验:
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 文件:
[
{
"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"
}
]
}
]
我现在的问题是,我不知道如何返回每个问题的所有五个答案。我希望你能帮助我。 :)
【问题讨论】:
标签: ruby-on-rails json api controller nested