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:
Create a controller to handle the request
With a simple shell command you can create a controller. Access the project folder and type something like (see shell commands for better understanding):
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 calledindex) for later run your service (that will contain your script). So you have a controller like:Create a router rule to foward the request to created controller
Access your
config/routes.rbfile and add to it the following line:If you want to understand more about Rails routing DSL you can check it out here.
Create the service
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.
Update view
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: