bronzeson bronzeson - 7 months ago 15
Ruby Question

Call Ruby function from HTML button without going to a new page

I am new to Ruby and web development in general.
I have many buttons that I want to do the same function but with different parameters.
However, to test it all I would like to do is call a very simple function in my controller (called gallery_matches_controller.rb)

In index.html.erb:

<%= button_to "Confirm", gallery_matches_path, action: "pleaseWork"%>

In routes.rb:

match 'gallery_matches/pleaseWork', to: 'gallery_matches#pleaseWork', via: [:get, :post]

In gallery_matches_controller.rb

def pleaseWork
puts "hello"

I am getting this error: ActionView::MissingTemplate
I assume I am getting it because something is up with my routes.rb line, but I cannot figure it out. I've tried to follow people's examples, but none of them seem to work.


Instead of

puts "hello"


render text: "hello"

The error message says a template is missing, because Rails automatically tries to render (output) a template named the same as your controller and action, if you don't tell it to output something else.

So in this case, it wants to automatically render a template like gallery_matches/pleaseWork.html.erb. If you tell it explicitly to render some text, it will do that instead and not look for a template.

On a side note, please_work would be more conventional than pleaseWork. Rails makes some assumptions about naming ("convention over configuration") so you may run into problems if you don't follow the standard naming.

Also, I don't think

<%= button_to "Confirm", gallery_matches_path, action: "pleaseWork"%>

will route to the expected controller. You could do

<%= button_to "Confirm", controller: "gallery_matches", action: "pleaseWork"%>