i have a search form on my site that allows a user to search by many different facets such as city, price range, size, etc.
the form submits as a GET so the form parameters are in the URL.
they end up being quite ugly:
/searches?utf8=✓&city_region=vancouver&property_type_id=1&min_square_footage=0&max_square_footage=15000
(they're actually even worse because the search parameters are part of a model so there are lots of encoded ['s and ]'s in the URL as well)
what i would like to do is instead have the form generate a URL like:
/searches/vancouver/office?square_footage=0-15000
where some of the parameters are placed into the URL path itself while others are left in the query parameters (in a slightly more readable format).
what would be the best way to handle this in a rails application? all i can think of is using javascript code on the form submit to manipulate the URL that the form submits to.
You can add to your controller this condition:
if params[:utf8]
redirect_to "/searches/#{params[:city_region]}/..."
end
All you need is to create a routing for this kind of page.
If you're on Rails 3:
match '/search(/:city(/:property_type(/:min_square_footage(/:max_square_footage)))' => 'search#index', :as => :search
(those parentheses refer to some variables being optional)
Then you can call it in your view with something like:
= link_to 'Search', search_url(:city_region => 'Vancouver', :property_type_id => 5, :min_square_footage => 0, :max_square_footage => 15000)
TLDR: The only way you can do this is by using an ajax on the form and then a redirect.
Setup the click event on your search button to trigger an ajax form post to a controller method.
Then use the magic in Jack's answer and call a redirect using your friendly url you generate... Just remember that if you want google to find your friendly url's you'll need to have them on a page somewhere statically. If you don't care about SEO then you solution should be pretty simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With