2

Some clients will have 30 questions and answers, some will have 20 and some will have 10. Those that have 10 or 20 can increase to the next level. In the controller i need to fill in for the answers that are missing. I had hoped to create one array in the controller with the question and answer matched and then send one array to the view.

@questions = Question.order("qtype, position")
@answers = Answer.where(user_id = current_user.id)

@questions.each do |q|
   @qa[q,0] = q.question
   @qa[q,1] = @answers.find_by_question_id(q.id)
   if @qa[q,1].empty?
      @qa[q,1] = 0
   end
end

I am getting "undefined method `question'." Don't know what i am doing wrong.

Thanks.

2
  • My answer addresses why you get the undefined method, but I feel like it's incomplete in the grand scheme of what you're trying to accomplish. What is @qa? Commented May 3, 2011 at 15:00
  • @McStretch, i was attempting to put the question (string) and the answer (integer) in a new array,... @qa. Commented May 3, 2011 at 15:51

2 Answers 2

4

You are calling .question on a Ruby Array (@questions), which does not have a question method.

The block argument q is the individual question that you want to access on each iteration.

Sign up to request clarification or add additional context in comments.

1 Comment

oh bother... its all in the details.
1

You can do this very easily in ruby using map:

@qa = @questions.map { |q| [q, @answers.find_by_question_id(q.id)] }

Since you have already loaded a correctly filtered answer array, it's actually more performant to do this:

@qa = @questions.map { |q| [q, @answers.detect {|a| a.question == q}] }

You would do well to spend some time reading up about Array and Enumerable in ruby.

4 Comments

thanks! Tonight i'll study array and enumerable via Google Search. Thanks for the feedback.
if i am getting this correctly, @qa then doesn't contain the question and the answer. It places the answer in @qa and assures that it matches the @question iteration. Correct?
also, if i am getting this correctly, if there is no answer for the question it doesn't the answer to 0.
I'm not sure what you're trying to do with 0. The answer will be nil if there isn't one, which is more idiomatic in ruby. You could do something like [q, @answers.detect {...} || 0] if you really want 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.