I want to make a ruby function called within rails. I followed this question, but I get redirected to
http://localhost:3000/my_func?arg=arg
which I don’t want. I only want to execute the function when the button is clicked, but remain on the same page!
EDIT:
I modified the code, or better yet, made a scratch site just to solve this. I only did:
rails new eraseme
cd eraseme
rails g controller public home
app/controllers/public/home.html.erb
class PublicController < ApplicationController
def home
end
def my_func
end
end
app/views/public/home.html.erb
<%= button_to "Button", {:action => "my_func", :arg => "arg"} %>
What I want to do, is execute my_func when I click the button. But when I click, I get
No route matches {:action=>"my_func", :arg=>"arg", :controller=>"public"}
So, from what I can tell. I think you want to make a button that will send an AJAX/HTTP request to the Controller in order to call a function, that won’t return a HTML file at completion.
In order to accomplish this, you must do the following.
1.) Set the HTTP routing for this call, this is within the config/routes.rb file.
This allows your application to direct any HTTP requests with the following URL to call your method within the controller. Your button_to method will send this call with that URL due to the :action => “my_func” param.
2.) Also include the :remote => true, :form => { “data-type” => “json” } as more parameters to the button_to method.
This will transform the button from a traditonal HTTP request to an HTTP Request via AJAX request.
Let me know how this works, I think there are alternatives to using AJAX in this case, if its a very simple method then you can perhaps include it within the view as erb.