如果我理解正確,那麼你的模型設置像這樣:
Program hasMany Module hasMany QuizContent hasMany QuizQuestion
或者更簡單地說:
Program hasMany Module hasMany Quiz hasMany Question
可以有相當多的思考中這些應用程序,所以很難告訴你如何在不知道更多問題的答案的情況下構造這個結構:
- 用戶可以不止一次地進行測驗嗎?
- 用戶可以回到他們已經回答的問題嗎?
- 答案是否單獨保存?
- 結果保存起來,然後存儲在結尾?
- 結果是否存儲在數據庫中?
- 是結果簡單地通過電子郵件發送過的地方?
假設要嚴格控制問題明顯,這使用戶能夠回去使用他們的瀏覽器控件,拿在會話,而不是數據庫中的狀態(不完整的測驗),你可能會接近它是這樣的:
class QuizController extends AppController {
# allow user to do a quiz
function do($id) {
# do something with each answer submitted
if ($this->data) {
// validate, save to database, or store in session until the end
$questionNumber = $this->Session->read('Quiz.question');
$this->Session->write('Quiz.question', $questionNumber + 1);
$this->redirect(array('action' => 'do', $id));
}
# get the quiz (and questions)
$quiz = $this->Quiz->find('first', array(
'conditions' => array('Quiz.id' => $id),
'contain' => array('Question'), // if using Containable
));
# quiz doesn't exist
if (!$quiz) {
$this->cakeError('error404');
}
# get the question number
$questionNumber = $this->Session->read('Quiz.question');
# quiz hasn't been started
if (!$questionNumber) {
$questionNumber = 1;
$this->Session->write('Quiz.question', $questionNumber);
}
# get the question
$question = Set::extract("/Question[$questionNumber]", $quiz);
# there are no more questions
if (!$question) {
// finalize quiz, save to database, redirect to obvious place
$this->Session->setFlash('Quiz complete');
$this->redirect(array('action' => 'index', $quiz['Quiz']['id']));
}
# set variables to the view
$this->set(compact('quiz', 'question'));
}
}
注:在上面我改名爲模型測驗和問題,提高readabilty的例子。
是的,這是正確的,但我如果用戶完成測驗在quiz_questions – baker 2009-12-21 03:39:17
爲什麼是邏輯存在,它記錄的代碼?測驗內容應該是唯一知道測驗是否已完成的地方。測驗內容應該有一個測驗/測驗問題的列表。 – Woot4Moo 2009-12-21 03:40:45
我想這是我設計中的一個錯誤。在用戶完成quiz_question後,流程應該放在哪裏?我的意思是在什麼控制器中? – baker 2009-12-21 03:49:50