创建一个在测验中发布答案的宁静路线

时间:2013-11-13 08:59:48

标签: ruby-on-rails rest

我正在开发课程申请表。每门课程都有一章,每章都有一个小测验。 对于测验我希望用户在多项选择题上发布答案(见截图)

enter image description here

但是,我无法弄清楚我应该发布哪种控制器操作方法。问题显示在问题#show action方法中,那么用户应该将问题的答案发布给问题控制器,但是接下来应该采取哪些措施?或者他应该将它发布到AnswersController?如果是这样的话?这是一个帖子,但他没有创建一个动作,对吗?

正如您所看到的,我对如何使“用户回答问题”方案尽可能安全感到困惑。

我的问题模型如下所示:

class Question < ActiveRecord::Base
  belongs_to :quiz
  has_many :answers, dependent: :delete_all
  validates_presence_of :title

  def self.subsequent_question(previous_question)
    where("id > ?", previous_question).first
  end

  def self.is_last?(question_id)
    question = Question.find(question_id)
    last_question = Question.last
    if question.id == last_question.id 
      return true
    else
      return false
    end
  end
end

QuestionsController:

class QuestionsController < ApplicationController
  def show
    if Question.is_last?(params[:id])
      question = Question.find(params[:id])
      redirect_to quiz_complete_path(id: question.quiz_id) 
    else
      @question = Question.subsequent_question(params[:id])
      @quiz = Quiz.find(params[:quiz_id])
      @chapter = Chapter.find(@quiz.chapter_id)
      @course = Course.find(@chapter.course_id) 
    end
  end
end

答案模型:

class Answer < ActiveRecord::Base
  belongs_to :question
  validates_presence_of :title
  validates_uniqueness_of :is_correct, conditions: -> { where(is_correct: true) }
end

AnswersController:

class AnswersController < ApplicationController
  def check_answer
    @answer = Answer.find(params[:id])
    question = Question.find(@answer.question_id)
    if Question.is_last?(question.id)
      redirect_to quiz_complete_path(id: question.quiz_id)
    else
      next_question = Question.subsequent_question(question.id)
      redirect_to show_question_path(id: question.quiz_id, question_id: next_question.id)  
    end
  end
end

感谢您的帮助,

安东尼

0 个答案:

没有答案