Question

Not sure how to frame this so here goes....

I have the following link_to tag:

<%= link_to("My test title",{:controller=>"search", :action=>"for-sale", :title => listing.title, :search_term => search_term, :id=> listing.id}) %>

and the following custom route in my routes.rb file:

map.connect ':controller/:action/:title/search_item/:id', :controller=>'search', :action=>'for_sale' 

which generates a very nice SEO friendly URL:

/search/for-sale/sometitle/searchterm/123456

How can I remove the :action param from both, the problem is when I take out the :action option & change my link_to tag to:

<%= link_to("My test title",{:controller=>"search", :title => listing.title, :search_term => search_term, :id=> listing.id}) %>

and my custom route to:

map.connect ':controller/:title/search_item/:id', :controller=>'search', :action=>'for_sale' 

The URL generated is no longer SEO friendly and very ugly:

/search?title=test&search_term=test&id=1141409

My custom route is redirecting to the correct action within the controller so there is no need for action option to be in the URL. Anytime I remove or rename the :action option to something else - the URL gets "distorted", do you know how I can do this?

Been trying a number of options but nothing seems to work.

Thanks!

Was it helpful?

Solution

Firstly, your route ':controller/:title/search_item/:id' doesn't have :search_term parameter, but you are trying to pass it in link_to :search_term => search_term

Secondly, if you are always using controller 'search', you do not need to pass it as a parameter.

So, your route probably becomes 'search/:title/:search_term/:id'

Also, try using named routes:

map.search 'search/:title/:search_term/:id', :controller=>'search', :action=>'for_sale'

<%= link_to("My test title", search_path(listing.title, search_term, listing.id)) %>

Edit: optional parameters

You can supply default value for parameters at the end of the route.

So, if you set

map.search 'search/:title/:search_term/:id', :controller=>'search', :action=>'for_sale', :id => nil, :search_term => nil

You can create url without id: search_path(listing.title, search_term) Or without both id and search_term: search_path(listing.title)

If you want to make only :search_term optional, put in at the end of the route:

map.search 'search/:title/:id/:search_term', :controller=>'search', :action=>'for_sale', :search_term => nil
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top