简体   繁体   中英

how to link form_tag to button rails 4

I have a selection box on my page, and when I click the submit button I want to take the selection choice to the server as either a post or get variable (I don't think it matters). How do I link this form:

<%= form_tag(store_rates_path, method: 'get') %>
  <%= label_tag(:year, "From (year)") %>
  <%= select_tag(:year, options_for_select(get_select_options(1980, 2014))) %>

to this button:

<%= button_tag(link_to("Get Rates", store_rates_path))%>

You can use rails submit_tag helper

<%= form_tag(store_rates_path, method: 'get') %>
  <%= label_tag(:year, "From (year)") %>
  <%= select_tag(:year, options_for_select(get_select_options(1980, 2014))) %>
  <%= submit_tag "Get Rates" %>
<% end %>

OR

If you want to use a link or button to submit your form parameters then you can use some js magic to achieve it:

<%= form_tag store_rates_path, id: "store-form", method: 'get' %>
  <%= label_tag(:year, "From (year)") %>
  <%= select_tag(:year, options_for_select(get_select_options(1980, 2014))) %>
  <%= link_to "Get Rates", "#", id: "store-form-btn" %>
<% end %>

$(document).on("click","#store-form-btn",function(e){
  e.preventDefault();
  $("#store-form").submit();
});

You only need to provide the path to the form_for method, to link it to the rates action of your stores controller:

<%= form_tag(store_rates_path, method: "get") do %>
  <%= label_tag(:year, "From (year)") %>
  <%= select_tag(:year, options_for_select((1980..2014).to_a)) %>
  <%= button_tag "Get Rates" %>
<% end %>

In your rates action you can then retrieve the :year parameter passed as follows:

def rates
 @year = params[:year]
end

You also need to define the route in your routes.rb file as follows, if you haven't yet:

get 'stores/rate', to: 'stores#rate', as: 'store_rates'

IMPORTANT

Just note that if the rates belong to a specific store, meaning the url is something like stores/1/rate then the above get must be stores/:id/rate , which also means you need to pass the store.id to the store_rates_path in your form: store_rates_path(@store)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM