我有一个应用程序,您可以在其中下载测验。每个测验都有多个问题。每个问题有五个可能的答案。这是我的模型: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