rails dynamically generate a form -
i'm pretty new whole rails mvc concept, , i've been tasked creating form following:
- takes test number
- shows how many sections there per test (this constant, 4)
- allows region user enter in responses each question in section. number of questions in each section changes depending on test number get.
i have view looks this:
= form_for [@answer_sheet] |f| =f.collection_select(:test_prep_number, exam.find(:all),:test_prep_number, :test_prep_number, {:include_blank => 'select test prep number'}) =f.fields_for :answer_sections |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'
my controller looks this:
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
the issue i'm having right can't seem wrap head around creating correct number of radio buttons. far, i've managed generate 1 question per section.
i'm assuming i'll need loop (which require query find how many questions per exam section).
edit: adding models requested
answer sheet model
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
answer section model
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 }
i recommend tweaking models breaks choice users answer:
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
Comments
Post a Comment