Sunday, March 9, 2008

How to disable submit button parameter in Rails

Here's a quick tip for Rails I've just learned from Railscast #37: Simple Search Form: when you submit a form in Rails, submit button parameter gets passed by default and it can be kinda annoying when you don't need it. For example by submitting this form:
<% form_tag( '/search', :method => 'get' ) do %>
  <%= text_field_tag :search_str %>
  <%= submit_tag "Search" %>
<% end %>
You get following parameters in URL: ?search_str=something;commit=Search

Let's say we don't need the commit=Search parameter. Fortunately, it's
really easy to get rid of it. Default name of submit_tag's parameter is "commit" and it's set by :name key. If you set it to nil, the parameter won't get pass. So just change the submit_tag helper to this:
<%= submit_tag "Search", :name => nil %>
And you get following parameters when submitting: ?search_str=something