我有一个应用程序,您可以下载测验。每个测验都有多个问题。每个问题都有五个可能的答案。这些是我的模特:
首先是测验模型:
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发出请求,然后成为测验,其中包含相应的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文件:
[
{
"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"
}
]
}
]
我现在的问题是,我无法弄清楚如何为每个问题返回所有五个答案。我希望你能帮助我。 :)
答案 0 :(得分:0)
在Quizz.rb
def as_json
super(include: { questions: { include: :answers } })
end
和
def quiz_content
@quiz = Quiz.includes(questions: :answers).find(params[:id])
render json: @quiz.as_json
end
答案 1 :(得分:0)
好的,我自己找到了解决方案:
def quiz_content
@quiz = Quiz.where('id = ?', params[:id])
render json: @quiz, include: ['questions', 'questions.answers']
end
我必须在序列化器中添加关联:
class AnswerSerializer < ActiveModel::Serializer
attributes(:id, :question_id, :answer, :correct_answer, :order)
belongs_to :question
end
class QuestionSerializer < ActiveModel::Serializer
attributes(:id, :quiz_id, :question)
belongs_to :quiz
has_many :answers
has_many :game_questions
end
class QuizSerializer < ActiveModel::Serializer
attributes(:id, :title, :abstract, :category_id, :download)
has_many :questions
end