Slippery John
Slippery John

Reputation: 757

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?

Upvotes: 30

Views: 61565

Answers (5)

Mika Yeap
Mika Yeap

Reputation: 43

It's as easy as adding method_controller_path to the HTML.
For instance, I have a route filaments/new, and to add a button that links to it from any view:
<%= button_to "Add", new_filament_path, method: :get %>

Upvotes: 1

Sai Ram Reddy
Sai Ram Reddy

Reputation: 1089

 <%= button_to 'Invite a user', new_project_invite_path, method: :get, remote: true, class: 'btn primary' %>

If you don't want it to be an Ajax call then you can remove remote: true

Upvotes: 4

richardsonae
richardsonae

Reputation: 2087

Another option is to create a route for your action and call it that way. Forgive me, I'm not sure what your home_controller.rb is doing. If it is the controller for your home page, I believe a pages_controller.rb with a home method is more conventional for Rails.

If that were the case, and assuming the method you want to call is named call_action,

Your pages_controller.rb would look something like:

class PagesController < ApplicationController
  #...

  def call_action
    <<does something really nifty>>
  end

end

Your config/routes.rb would look like:

AppName::Application.routes.draw do
  #...

  resources :pages do
    collection do
      get :call_action
    end
  end

end

The link on your home page at views/pages/home.html.erb would look like this:

<%= link_to "Call Action", call_action_pages_path %>

You should run rake routes on your command line to make sure you have the correct route, then stick _path on the end of it.

If you want your link to be a button, you can create a styled class for that and append it to your link:

<%= link_to "Call Action", call_action_pages_path, class: "button" %>

Or wrap it in a styled class:

<div class="button">
  <%= link_to "Call Action", call_action_pages_path %>
</div>

Upvotes: 4

spullen
spullen

Reputation: 3317

<%= 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'

Upvotes: 25

Deej
Deej

Reputation: 5352

Take a look at button_to.

Example shows you can do something like

<%= button_to "Some Button", :method=> "someButton" %>

Upvotes: 4

Related Questions