I have been trying to use routes.rb for creating a URL /similar-to-:product (where product is dynamic) for my website. The issue is that routes.rb readily supports URLs like /:product-similar but doesn't support the former because it requires :product to be preceded with a separator ('/' is a separator but '-' isn't). The list of separators is in ActionController::Routing::SEPARATORS.

I can't add '-' as a separator because :product can also contain a hyphen. What is the best way of supporting a URL like this?

One way that I have successfully tried is to not use routes.rb and put the URL parsing logic in the controller itself, but that isn't the cleanest way.


I'm a little confused, but could you maybe add "to-" as a seperator?

seems like rails supports only a single character as a separator
+2  A: 

I would refactor your URLs so that they're simply "similar-to/product"

Ian Terrell
+1  A: 

In fact you can add - as a separator, then use route globbing.

map.similar_product '/similar-to-*product', :controller => 'products', :action => 'similar'

then, in ProductsController#similar

@product = Product.find_by_slug params[:product].join('-')

Though refactoring does seem nicer, since with this approach you'll need to specially handle all slugs that can contain hyphens.

Leonid Shevtsov
That isn't working. The url doesn't get matched to this route at all. I guess that is because even in this case *products should come after a separator.
+1  A: 

An easy solution is using a routing filter. See README for details.

With routing filter you can have a url /similar-to-:product, preprocess it to /similar-to/:product before it gets to routing recognition. You'll also want to post-process generated paths back from /similar-to/:product to /similat-to-:product.