Topic: saving Data [SOLVED but not clean]

I have a form that i am generating dynamically

so it has N number of questions and each question should have a Answer.

my params data looks like

params 
{"utf8"=>"✓", "authenticity_token"=>"RmioqBWZoMVUtpy1IDcJ6kp29mfr05la4Rpdd61pPv4=", "question_38"=>"a", "question_39"=>"v", "controller"=>"questions", "action"=>"message", "id"=>"2"}

and i have to convert that to look like

a question_group_id: so that i can then get all the questions that where ask at the same time
a question_id : that links to the question that was ask
a content: what the person actually answered

Ansewer.new(:question_group_id => 1, :question_id => 38, :content=> "a").save
Ansewer.new(:question_group_id => 1, :question_id => 39, :content=> "v").save

Last edited by moiseszaragoza (2012-09-28 15:27:44)

Re: saving Data [SOLVED but not clean]

Try to do something like this

count = 0-
      params.each do |p|
        key = p.first
        val = p.last
        if key.include? "question"
          question_id = p.first.split("_")
          if count == 0
             # you still have to find out how to get the question_group_id
             #require 'ruby-debug'; Debugger.start; Debugger.settings[:autoeval] = 1; Debugger.settings[:autolist] = 1; debugger-
          end
          Answer.new(:question_group_id =>1, :question_id => question_id.last , :content => val).save
          count = count +1
        end
      end
      flash[:success] = t(:message_taken)
      redirect_to questions_path

Re: saving Data [SOLVED but not clean]

to get the line that you are missing you can count the total count of the Answer's table like

question_group_id = Answer.count + 1

full code

params.each do |p|
        key = p.first
        val = p.last
        if key.include? "question"
          question_id = p.first.split("_")
          if count == 0
            question_group_id = Answer.count + 1
          else
            question_group_id = Answer.count + 1 - count
          end
          Answer.new(:question_group_id => question_group_id, :question_id => question_id.last , :content => val, :account_id => current_user.account.id, :user_id => current_user.id).save
          count = count +1
        end
      end