drewwyatt
drewwyatt

Reputation: 6027

How do I call PARAM values nested in a multi-dimensional array?

Ruby: 2.0

Rails: 4.0

I am attempting to pull answer choices from my quiz application. Users select the radio button for =what they believe to be the correct answer in this form:

<%= form_tag do |f| %>
    <%= hidden_field_tag :quiz_id, @quiz.id %>
    <% @quiz.questions.each do |question| %>
        <div class="question">
            <p><%= question.text %></p>
            <ul>
                <% question.answers.each do |answer| %>
                    <% if answer.text.length > 0 %>
                        <li>
                            <%= radio_button_tag "[questions][#{question.id}]selected_answer", answer.id %>
                            <%= answer.text %>
                        </li>
                    <% end %>
                <% end %>
            </ul>
        </div>
    <% end %>
    <%= submit_tag "Score this Quiz" %>
<% end %>

These parameters seem to be coming through okay - you can see them in the log using Spike:

Spike Screenshot

However, I cannot figure out how to make a call to these parameters, here is my controller logic:

def score
   @answers = []
   @quiz = Quiz.find(params[:quiz_id])
   @quiz.questions.each do |question|
       @answers << params[:questions[question.id][:selected_answer]]
   end
end

But that throws the error: no implicit conversion of Symbol into Integer

How do I go about grabbing the selected_answer for each question?

Update:

I have made the changes recommended in the comments:

form

<%= radio_button_tag "questions[#{question.id}][selected_answer]", answer.id %>

controller

@quiz.questions.each do |question|
    @answers << params[:questions][question.id][:selected_answer]
end

This is now giving me this error: undefined method[]' for nil:NilClass` On this line:

@answers << params[:questions][question.id][:selected_answer]

Upvotes: 0

Views: 568

Answers (2)

gregates
gregates

Reputation: 6714

This just looks like a typo. Should be:

@answers << params[:questions]["#{question.id}"][:selected_answer]

Note the slightly different placement of brackets.

Also, we may need to translate the question.id to a string, since the params hash will have string keys (it's a HashWithIndifferentAccess, so you can also use symbols, but I think not integers).

Upvotes: 3

fotanus
fotanus

Reputation: 20116

Most likely you are looking for

<%= radio_button_tag "questions[#{question.id}][selected_answer]", answer.id %>

And you your controller

@answers << params[:questions][question.id][:selected_answer]

You can see exactly the content of params in the log. Take a look at questions and you will be able to see the exact structure in ruby code.

Upvotes: 0

Related Questions