How to bind data properly?

11 views
Skip to first unread message

Sanjay Giri

unread,
Jun 25, 2017, 2:33:15 AM6/25/17
to Ruby on Rails: Talk
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! 


Reply all
Reply to author
Forward
0 new messages