Coda Chang Coda Chang - 1 month ago 18
Ruby Question

Rails number_field_tag pass hash value

I am confused about setting the form name and its params.

Here is my form

<%= form_tag('/monster) do %>
<% @monsters.each do |monster| %>
<tr>
<th scope="row"><%= monster.id %></th>
<td><%= t("backpack.mon_infos.#{monster.name}.name") %></td>
<td><%= number_field_tag "monster[[#{monster.id},#{monster.name}]]", 0 %></td>
</tr>
<% end %>
<% end %>


The params will get this

"monster" => {
"1,MonsterA" => "10",
"2,MonsterB" => "25"
}


But I want it to be like

"monster" => {
"1" => {'name': 'MonsterA' ,'quanty': "10"},
"2" => {'name': 'MonsterB' ,'quanty': "25"}
}

Answer

Can you try this:

<%= form_tag('/monster) do %>
  <% @monsters.each do |monster| %>
    <tr>
      <th scope="row"><%= monster.id %></th>
      <td><%= t("backpack.mon_infos.#{monster.name}.name") %></td>                
      <%= hidden_field_tag "monster[#{monster.id}][name]", monster.name %>
      <td><%= number_field_tag "monster[#{monster.id}][quantity]", 0 %></td>
    </tr>
  <% end %>
<% end %>