Creating a new Ruby on Rails action to update one Boolean value each time the link is followed

82 views Asked by At

I have been Googling around for an answer to this for about an hour now after trying to get it to work with what i know about rails for quite some time and decided enough was enough. On my index page i want to create a button that acts like the default 'delete' action but instead it will update a boolean value. This is my action in my controller:

def update_monitor_state
  @server_monitor.paused = not @server_monitor.paused
  redirect_to server_monitors_url
end

I would show you my routes but i have no idea how to get it to do what i want and i have the basic 'resources :server_monitors' after trying everyone's routes that would work for adding a new show page for their basic blog site. I just know the URI pattern should be '/server_monitors/:id(.:format)' and the controller action 'server_monitors#update_monitor_state' and i would like to call it in the views like how 'delete' is called.

<% @server_monitors.each do |monitor| %>
  <tr>
    <td><%= monitor.monitor_name %></td>
    <td>
      <% if monitor.paused %>
        <%= link_to 'Start', monitor, method: :update_monitor_state %>
      <% else %>
        <%= link_to 'Pause', monitor, method: :update_monitor_state %>
      <% end %>
    </td>
    <td><%= link_to 'Destroy', monitor, method: :delete %></td>
  </tr>
<% end %>
1

There are 1 answers

3
Aetherus On

Well, you need some serious help about Rails. There are some rules:

No variables can be used to store server status.

No doubt local variables can't do this.

Instance variables of controllers don't do the work, because a controller instance only lives during a single request.

In production environment, multiple Rails processes will be spawned to achieve concurrency. You don't know which process serves your current request, and your next request, and ... Since the processes don't share memory (well, you may say Copy on Write, but that only shares memory that has not been changed yet), class variables and global variables don't do the job either.

The only way to store server status is to use some sort of external storage like a database, which is shared among all Rails processes.

Redirection is not rendering views

The redirect_to helper just sends responses with no body but a Location header with a URL in it. When the browser receives such response, it will immediately send a new request to that URL. A new request compromises all controller instance variables, because a brand new controller instance is created to handle the new request.