Tuesday, November 16, 2021

[SOLVED] Ruby on Rails how to create multiple buttons for starting and stopping a program

Issue

I'm trying to create an application on Linux CentOS 7 using Ruby on Rails (Ruby 2.4.1 & Rails 5.2.0) where it displays a program that's running and gives you several buttons to stop or start the program. Would I do this in a form or would this be some other kind of process? I've looked this up for a while and couldn't find an answer. I'm also not sure how to send this code to start or stop the program, but I'm guessing I will need JavaScript for this task.

This is the code I've gotten from the Getting Started with Rails tutorial:

<%= form_with scope: :article, url: articles_path, local: true do |form| %>
  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

http://guides.rubyonrails.org/v5.2/getting_started.html

However, I don't know how to put a button outside of a submit button like this, and I cannot edit the text on the button's label. Also, to reiterate, I'm not sure if a form is what's needed for this task.


Solution

No, you don't need a form. Just do something like

<%= link_to "Start", your_start_url, id: 'start-button', class: 'btn btn-primary', remote: true %>

and

<%= link_to "Stop", your_stop_url, id: 'stop-button', class: 'btn btn-danger', remote: true %>

You can style the links to look like a button. Of, if you're using Bootstrap, then Bootstrap will do the styling for you.

You probably want to set the disabled class for the links depending on whether the program is currently running or not. Given remote: true, you can use JS to reset the disabled class based on what the user clicks (using an .on 'click' or .click handler).

I suppose you could do this entirely on the front end. In which case you might do something like:

<div id: 'start-button', class: 'btn btn-primary'></div>

And then in your JS, you could do something like (using JQuery and coffescript):

$('#start-button').on 'click', (e) =>
  # do some stuff

Personally, I prefer to handle stuff like third party programs on the back end. But, skin the cat however you prefer.



Answered By - jvillian