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

前端 未结 5 533
日久生厌
日久生厌 2020-12-15 17:30

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 experime

相关标签:
5条回答
  • 2020-12-15 18:11

    Take a look at button_to.

    Example shows you can do something like

    <%= button_to "Some Button", :method=> "someButton" %>
    
    0 讨论(0)
  • 2020-12-15 18:18

    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>
    
    0 讨论(0)
  • 2020-12-15 18:27
    <%= 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'
    
    0 讨论(0)
  • 2020-12-15 18:27

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

    0 讨论(0)
  • 2020-12-15 18:28
     <%= 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

    0 讨论(0)
提交回复
热议问题