2

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

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Such a simple solution ... The only downside compared to my solution I see here is that it does not support "pretty" urls in case you want to have something like /users/thomas/... instead of users?name=thomas... without url rewriting. +1 for the simplicity of your solution
0

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.

1 Comment

Btw. I might be a cool addition to your code to add some javascript, e.g. in the onchange event of your select box, which simply does a "submit()" - this makes the "Go" button obsolete (if you expect your users to have js enabled, that is ...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.