hidekinogo
hidekinogo

Reputation: 21

How to loop through forms in Rails?

I am trying to create a Rails app where people can pick which sports teams will win that day. I can display all of the day's games and I can create a form to pick the winner for one game, but I am thus far unable to meld those two together to allow the user to see a list of all of the day's games with a radio button beside each team and make a selection on each of the games, then click a single submit button.

I have so far tried the below and several variations thereof.

<% @games.each do |game| %>

  <%= form_for @pick, url: {action: "index"} do |f| %>
    <p>
      <%= f.label(game.home)%>
      <%= f.radio_button(:winner, game.home) %>
      <%= f.label(game.away)%>
      <%= f.radio_button(:winner, game.away) %>
    <%= f.submit "Pick" %>
  </p>
  <% end %>

<% end %>

Here's what I am aiming for:

Team A [X] vs. Team B [ ]
Team C [ ] vs. Team D [X]
Team E [ ] vs. Team F [X]

[Submit]

Also, is there a better way to do this using a gem or something else more straightforward?

Upvotes: 0

Views: 269

Answers (1)

Pavan
Pavan

Reputation: 33542

You shouldn't loop through the form. Instead loop through the fields.

<%= form_for @pick, url: {action: "index"} do |f| %>
  <% @games.each do |game| %>
    <p>
      <%= f.label(game.home)%>
      <%= f.radio_button(:winner, game.home) %>
      <%= f.label(game.away)%>
      <%= f.radio_button(:winner, game.away) %>
    </p>
  <% end %>
  <%= f.submit "Pick" %>
<% end %>

Upvotes: 1

Related Questions