I have a scaffold that generates a table of basketball teams. I want to implement a button in the table that increases the number of wins for a team and another for the losses.By default, both are set to 0 in the controller. Should I implement a method in the controller or the view (add_wins and add_losses)? If so, how would it look like? Thank You. This is the code for the body of the table in the view:
<tbody>
<% @teams.each do |team| %>
<tr>
<td><%= team.Name %></td>
<td><%= team.Color %></td>
<td><%= team.Players %></td>
<td><%= team.Wins %></td>
<td style="font-size: 20px"><%= button_to '+', method: :add_wins %></td> <!-- The method add_wins doesn't exist. -->
<td><%= team.Losses %></td>
<td style="font-size: 20px"><%= button_to '+',method: :add_losses %></td> <!-- The method add_losses doesn't exist. -->
<td><%= link_to 'Show', team %></td>
<td><%= link_to 'Edit', edit_team_path(team) %></td>
<td><%= link_to 'Delete', team, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
Not a fully copy-paste answer, but I'll try to explain the basics, so hopefully you can figure out the whole solution on your own.
First of all, I'd advise you against implementing separate add_wins
, add_losses
methods as these:
0
losses, click add
, something goes wrong with rendering the response, the counter has been updated to 1
, but the user goes back to the previous page, sees 0
again and clicks add
again, you'd end up on 2
instead of 1
.Instead, stick to the standard update
action with proper parameters.
Here are the docs for button_to
, you will have to set proper method
and params
. Your params
need to contain the next value for losses or wins and the team id. Additionally, you may wish to validate that somebody is not trying to send some arbitrary value for wins or losses. The method
you'll want to use is put
.