Submitting the rails form to a "friendly" URL

I have a search form on my site that allows the user to search for various aspects such as city, price range, size, etc.

the form is submitted as GET, so the form parameters are in the url.

they are ultimately pretty ugly:

/ search utf8 = βœ“ &? City_region = Vancouver & property_type_id = 1 & min_square_footage = 0 & max_square_footage = 15000

(they are actually even worse because the search parameters are part of the model, so there are a lot of encoded [and] in the URL)

what I would like to do instead has a form generating a URL, for example:

/ search / vancouver / office? = Area in square feet above sea level 0-15000

where some parameters are placed in the URL path, and the rest remain in the request 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 to use javascript code in the submit form to manipulate the url that the form represents.

+8
ruby-on-rails forms
source share
3 answers

You can add the following condition to your controller:

if params[:utf8] redirect_to "/searches/#{params[:city_region]}/..." end 
+6
source share

All you need to do is create routing for this page.

If you are on Rails 3:

 match '/search(/:city(/:property_type(/:min_square_footage(/:max_square_footage)))' => 'search#index', :as => :search 

(these brackets refer to optional variables)

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) 
+1
source share

TL; DR: the only way to do this is to use ajax on the form and then redirect.

Configure the click event on the search button to trigger an ajax form message for the controller method.

Then use the magic in Jack's response and call the redirect using your friendly URL that you generate ... Just remember that if you want Google to find your friendly URL, you will need to have them on the page somewhere statically. If you do not care about SEO, then the solution should be quite simple.

+1
source share

All Articles