rails 3 select drop down box
how can i make a select drop down box behave like a link in rails. by this i mean, when somebody selects an option from the list, it posts it in the URL. For example, if somebody selected their开发者_运维知识库 name was "Thomas" from the box, in the URL it would display ?name=Thomas
. how could i do this?
<%= form_tag(orders_path, :method => "get") do %>
Choose a state
<%= hidden_field_tag :id, "1" %>
<%= select_tag :state, options_for_select(us_states) %>
<%= submit_tag "Go" %>
<% end %>
but when i do it this way i get a bunch of extra information inside the url such as this:
?utf8=✓&id=1&name=Thomas&commit=Go
Thanks in advance
The reason all those other fields are being sent is because rails adds them by default to all of its helpers. The commit=Go
part comes from the submit_tag
helper and utf8=✓
is there because it's added by the form_tag helper. The simplest way to achieve what you need is to just not use the other form helpers:
<form action="<%= orders_path %>" method="get">
<%= select_tag :name, options_for_select(%w(John Jim Thomas)) %>
<input type="submit" value="Go">
</form>
By choosing "Thomas" and clicking on "Go", you'll only get ?name=Thomas
in your url. You could use the submit helper, though, as long as you set its name to nil
:
<form action="<%= orders_path %>" method="get">
<%= select_tag :name, options_for_select(%w(John Jim Jones)) %>
<%= submit_tag "Go", :name => nil %>
</form>
Good question and one I had a hiccup myself with lately. I ended up defining a new action in my controller which takes the response and simply redirects to the final url via redirect_to
. I also tried defining the redirection in my routes.rb directly (without the additional action in the controller), but did not have luck with that.
This might work as a workaround for you, but I'm also curious to see other (better) solutions.
精彩评论