我对整个rails MVC概念都很陌生,我的任务是创建一个执行以下操作的表单:
我的观点如下:
= 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 }
答案 0 :(得分: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