So i have a completely new ruby on rails app just made and i added a button with bootstrap. picture. I also have a simple script that prints out "hello".
simple.rb, which is in app/scripts/simple.rb
puts "hello"
Now can someone please explain and give me an example of how can i connect the script to the button i have. So when i click the button on the website, it does what the script is told to do. I have been searching for a full day and found that maybe i need to create a new controller/view/route for it? or "require 'file' ". Correct me if im wrong, thank you!
You will need to follow four steps in order to reach your 'script'. First of all I recomend you to read about Rails services pattern for a better practice. In my vision it fit your necessities.
Step by step:
With a simple shell command you can create a controller. Access the project folder and type something like (see shell commands for better understanding):
rails g controller hello
So now you will have a new controller called 'HelloController' inside controller's folder (app/controllers/hello_controller.rb
). You can check it out and notice it have no methods. First create a method (bellow I've done one called index
) for later run your service (that will contain your script). So you have a controller like:
class HelloController < ApplicationController
def index
# Your service goes here
end
end
Access your config/routes.rb
file and add to it the following line:
resources :hello, only: %i[index]
If you want to understand more about Rails routing DSL you can check it out here.
To create the specified service in order to run your so-desired script, I recommend you to follow the instructions given by Amin Shah. No reason to repeat what he said.
Now you just have to create a link to perform a GET request to your created route. You can use Rails link_to helper. Something like:
<%= link_to "Button", hello_index_path, class: "btn btn-primary" %>