Andru1989
Andru1989

Reputation: 180

Get value from hash param

At this time I have this field in the partial "_form.html.erb"

<% Pregunta.where("subpoll_id = ?", s.id).each.with_index do |i, index| %>
    <tr>
    <td>
            <%= f.input :descripcion, 
            :label => false, 
            :error => false,
            :input_html => {
            :name     => "pregunta[]",
            :class    =>'form-control input-sm',
            :value    => "#{i.descripcion}",
            :readonly => true,
            :style    => "
                border:hidden;
                background-color:white;"} %>
    </td>
    <td width="15%">
        <%= f.input :respuesta,
                :collection => Respuesta.where("pregunta_id = ?", i.id),
            :label      => false,
            :error      => false,
            :input_html => {
            :class =>'form-control input-sm',
            :name => "respuesta[]"} %>
    </td>
    </tr>

So as you see I get a hash with this :name => "respuesta[]" because that field repeats in the form depending of the number of "preguntas"

From my controller I'm getting the information this way

@respuesta  = params[:respuesta]

And my question is: How can I get an especific value of this hash for save it in a column table and for compare it with another's values

thanks for your help

Upvotes: 0

Views: 205

Answers (2)

Simptive
Simptive

Reputation: 987

You are getting identity less array of values, you can give identity to each value using following minor change that will be posted as array of hashes:

<% Pregunta.where("subpoll_id = ?", s.id).each.with_index do |i, index| %>
  .
  <%= f.input :respuesta,
    .
    :name => "respuesta[#{i.id}]"} %>
    .

You'll get params in the form:

{respuesta: [{pregunta_id: respuesta_value}, {pregunta_id: respuesta_value} .. ]}

Later, you can get specific values by:

params[:respuesta].each do |key_val|
  Pregunta.find(key_val[0]).update_attribute('respuesta', key_val[1])
end

If you need further level of specification for the values of respuesta, you can do something like this:

<%= f.input :respuesta, :collection => Respuesta.
  where("pregunta_id = ?", i.id).collect{|r| [r.val, r.id] }, ... 

Later you can get specific respuesta value by:

params[:respuesta][<pregunta_id>][<respuesta_id>]

Hope this will help!

Upvotes: 1

Jelkster
Jelkster

Reputation: 56

playing around with the following may help:

@respuesta.each_with_index do |(respuesta_key, respuesta_value), index|
   puts "Respuesta: #{index}" 
   puts "Key: #{respuesta_key}"
   puts "Value: #{respuesta_value}"
end

Upvotes: 1

Related Questions