Ruby on Rails Saturday, June 24, 2017

sendAnswers page is a survey page with questions and options.


    def sendAnswers
       
       
@questions = @homework.questions
       
       
   
end



The view for sendAnswers is

    = form_for :survey do |f|
     
- @questions.each_with_index do |q, i|
       
%p
         
%br  
         
= "#{i+1})"
         
= q.question
       
%p  
         
- if q.options.size == 0
           
= f.text_field 'answer_' + q.id.to_s, placeholder: 'Answer', class: 'form-control'
         
- else
           
- q.options.each do |o|
             
.radio
               
%label      
                 
= f.radio_button 'answer_' + q.id.to_s, o.option
                 
= o.option
             
     
= f.submit "Submit", class: 'btn btn-primary', data: {confirm: 'Are you sure you want to submit this homework?'}
         



The page posts to the following method which saves the answers to questions in database. 


   
def saveAnswers
           
       
@homework.questions.each do |q|
           
            aa
= Answer.new
            aa
.answer = params[:survey]['answer_' + q.id.to_s]
            aa
.question = q
            aa
.user = current_user
            aa
.homework = @homework
            aa
.save
   
       
end
   
        render
'complete'
   
end



        
As you can see above i am appending question ids to the questions in the view page to track which answer belongs to which question and in the save action i use the appended question ids to save the answer to respective question. I am wondering whether there is a better and more natural way of binding this and not doing it manually like i am doing. Can this be achieved using form objects? I appreciate any guide to this dilemma. Thanks! 


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/940a9c69-398d-4ca3-9ddc-7f6b938af894%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment