Using routes with forms


#1

i have a form that uses :method => ‘get’ to pass data to the
controller…

the form has one text field called “zipcode”…

i also have a route that looks like:

map.connect ‘find_place/:zipcode’, :controller => ‘find_place’, :action
=> ‘by_zip’

this will allow me to pass info on the url…

what i would like to do is have the form spit the “get” call so that it
follows the routing and looks like:

/find_place/90210

instead of:

/find_place/by_zip?zipcode=90210&commit=Find+a+Place%21

anyone have any ideas?

thanks!


#2

That should work, but you need to have that route first, before any
other route that will catch the params and build a URL.
I would do
map.connect ‘find_place/:zipcode’, :controller => ‘find_place’, :action
=> ‘by_zip’, :zipcode => /[0-9]{5}/
That will match your route only if the zip is a string of 5 digits.
-Jason


#3

Sergio R. wrote:

i have a form that uses :method => ‘get’ to pass data to the
controller…
the form has one text field called “zipcode”…

i also have a route that looks like:
map.connect ‘find_place/:zipcode’, :controller => ‘find_place’, :action
=> ‘by_zip’

this will allow me to pass info on the url…
what i would like to do is have the form spit the “get” call so that it
follows the routing and looks like:

/find_place/90210

instead of:
/find_place/by_zip?zipcode=90210&commit=Find+a+Place%21

anyone have any ideas?

thanks!

This won’t be possible without javascript. The fault lies with the
browser. The knows that that a form posted via “get” needs to have the
form data in the url. The the browser creates a query string out of the
form data and appends it the form action url.

The browser can’t read your routes.rb file, and wouldn’t be able to
parse it anyways. So the browser contructs the url in the only way it
knows how.

There are two ways around this, one server side and one client side:

Server Side:
You could detect the submission to the ugly url and redirect to the
right one with something like:

def by_zip
if request.request_uri =~ /?/
return redirect_to url_for(:controller => ‘find_place’,
:action => ‘by_zip’,
:zip_code => params[:zipcode])
end

...

end

Client side:
Use javascript to dynamically change what happens when the submit button
is clicked.

<%= submit_button “Submit”,
:onclick => “window.location.href =
‘#{/find_place/’+$(‘zip’).value” %>


#4

thanks so much!

i think i will go with the javascript version…

thanks again…