1

我对整个 Rails MVC 概念很陌生,我的任务是创建一个执行以下操作的表单:

  • 需要一个测试号
  • 显示每个测试有多少个部分(这是一个常数,总是 4)
  • 允许用户输入他们对部分中每个问题的回答的区域。每个部分的问题数量根据他们获得的测试数量而变化。

我的观点是这样的:

  = form_for [@answer_sheet] do |f|
      =f.collection_select(:test_prep_number, Exam.find(:all),:test_prep_number, :test_prep_number, {:include_blank => 'Select your test prep number'})
      =f.fields_for :answer_sections do |section_form|
         =section_form.label :section
              .form-inline
             =f.label :A 
             =radio_button_tag 'answer', 'A'
             =f.label :B
             =radio_button_tag 'answer', 'B'
             =f.label :C
             =radio_button_tag 'answer', 'C'
             =f.label :D
             =radio_button_tag 'answer', 'D'
             =f.label :E
             =radio_button_tag 'answer', 'E'

我的控制器如下所示:

def index
    @answer_sheet = AnswerSheet.build_with_answer_sections
    @answer_section = AnswerSection.new
    @section_count = AnswerSection.where("exam_id = ?", params[:test_prep_number).count
end

我现在遇到的问题是我似乎无法全神贯注地创建正确数量的单选按钮。到目前为止,我已经设法每个部分只生成一个问题。

我假设我需要一个 for 循环(然后需要一个查询来查找每个考试部分有多少问题)。

编辑:根据要求添加模型

答题纸型号

class AnswerSheet < ActiveRecord::Base
  attr_accessible :date, :raw_score, :test_prep_number, :answer_sections, answer_sections_attributes
MAX = 101
validates :test_prep_number, :presence => true
validates :raw_score, :presence => true, :numericality => { :greater_than_or_equal_to => 0, :less_than_or_equal_to => MAX}
validates :date, :timeliness => {:on_or_before => lambda { Date.current }, :type => :date}, :presence => true
belongs_to :user
has_many :answer_sections

答案部分模型

class AnswerSection < ActiveRecord::Base
  MAX = 30

  attr_accessible :section_score, :answers, :answer_attributes
  has_many :answers, :dependent => :destroy
  belongs_to :answer_sheet
  accepts_nested_attributes_for :answers

  validates :section_score, :presence => true, :numericality => { :greater_than_or_equal_to => 0,
:less_than_or_equal_to => MAX }
4

1 回答 1

0

我建议将您的模型调整为打破用户回答的选择:

class Test < ActiveRecord::Base
  belongs_to :user
  has_many :question

  attr_accessible :date, :test_prep_number

  validates :test_prep_number, :presence => true
  validates :date, :timeliness => {:on_or_before => lambda { Date.current }, :type => :date}, :presence => true
end

class Question < ActiveRecord::Base
  MAX = 30

  attr_accessible :question_text
  has_many :choices, :dependent => :destroy
  has_one :answer
  belongs_to :test
  accepts_nested_attributes_for :answers

end

class Choice < ActiveRecord::Base
  attr_accessible :question_id, :choice_text, :correct_choice
  belongs_to :question
end

class Answer < ActiveRecord::Base
  attr_accessible :choice_id
  belongs_to :user
  belongs_to :question 
end
于 2013-05-16T18:05:50.340 回答