Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a controller method from a button in rails 4

So I feel really stupid right now, but I can't seem to find an answer.

So I have a method which needs to be called EXACTLY once, and since this is only the experimental phase, I decided that a simple button should suffice. However, I can't seem to find out how to / if I can simply call the method from a button click.

The method is in home_controller.rb and the button is in index.html.erb

Any ideas? Or is this not something I can do?

like image 850
Slippery John Avatar asked Jun 21 '13 19:06

Slippery John


People also ask

What is a Rails controller?

The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services.

What is the difference between actioncontroller and ApplicationController in rails?

If you look at book_controller.rb, you will find it as follows − Controller classes inherit from ApplicationController, which is the other file in the controllers folder: application.rb. The ApplicationController contains code that can be run in all your controllers and it inherits from Rails ActionController::Base class.

What is Ruby on Rails controller?

Ruby on Rails - Controller. The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model.

What is the new method in rails?

The new method lets Rails know that you will create a new object. So just add the following code in this method. The above method will be called when you will display a page to the user to take user input.


2 Answers

<%= form_tag home_action_path, method: :post do %>   <%= submit_tag 'Call Action' %> <% end %> 

could also use a link

<%= link_to 'Call Action', home_action_path, method: :post %> 

or you can use button_to

<%= button_to 'Call Action', home_action_path, method: :post %> 

in your routes

post 'home/action' 
like image 143
spullen Avatar answered Sep 27 '22 03:09

spullen


Take a look at button_to.

Example shows you can do something like

<%= button_to "Some Button", :method=> "someButton" %> 
like image 20
Deej Avatar answered Sep 26 '22 03:09

Deej