Supporting URLs like /similar-to-:product in Ruby on Rails?
-
02-07-2019 - |
Question
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.
Solution
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.
OTHER TIPS
I would refactor your URLs so that they're simply "similar-to/product"
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
.
I'm a little confused, but could you maybe add "to-" as a seperator?