Home > Blockchain >  How to make a link that changes a variable in Rails
How to make a link that changes a variable in Rails

Time:03-21

I'm going through the Odin Project and the Ruby on Rails.org guides and still can't figure out how to make a link that updates a boolean from true to false. I'm seriously going insane over this.

I want to make a webpage that everyone puts in their name and it assigns each person a role in the game (like Innocent/Traitor roles in games like One night werewolf/ spyfall / trouble in terrorist town). Each player has a boolean called alive that stores if they are still in the game.

I'm still testing and learning stuff so right now I just want to add a link that when you click it, it changes that player's alive status from true to false. Way simpler than anything I've been able to find people asking about anywhere online. Here's my repo: https://github.com/esimunds/nerf_app

I just have a Player model, players controller, and player related views. The link in question is the last link in the index.html.erb view.

<p id="notice"><%= notice %></p>

<h1>Players</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Alive</th>
      <th>Wins</th>
      <th>Losses</th>
      <th colspan="4"></th>
    </tr>
  </thead>

  <tbody>
    <% @players.each do |player| %>
      <tr>
        <td><%= player.name %></td>
        <td><%= player.alive %></td>
        <td><%= player.wins %></td>
        <td><%= player.losses %></td>
        <td><%= link_to 'View', player %></td>
        <td><%= link_to 'Edit', edit_player_path(player) %></td>
        <td><%= link_to 'Delete', player, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        <td><%= link_to 'I/ve been shot', player, method: :put%></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Player', new_player_path %>

I just want the "I've been shot" link to change the respective player's alive variable to false, and then have the index view refresh to show the new alive status. I have no idea how or where to add any sort of methods that affect any of the data in the database. The tutorials only ever mention creating and deleting entire objects, and the only editing they teach is through a form which I currently use to add or edit the player names. I feel like this is such a basic question but I'm so lost.

CodePudding user response:

Add a new route

patch 'shot' => 'players#shot', as: :player_shot

Then a new controller action

def shot
  @player = Player.find(params[:id])
  @player.update(shot: true)
end

Then in the view

button_to 'Shot', player_shot_path(id: player.id), method: :patch, remote: true
  • Related