According to the Rails Routing Redirection guide, there doesn't seem to be an easy way to redirect a matched URL to another named URL within the routes file.
I wish I could redirect like this, or something similar, in my routes.rb without having specify the full url path ("/articles/%{id}") in the redirect function.
match "articles/:id" => "articles#show", :as=>'article'
match "articles/view/:id", :to => redirect(article_path)
Is there a plugin or gem that might provide this functionality?
My final solution included adding a function like the following based on the accepted answer.
# handles redirecting a matched URL to a named URL
# source_match = string to match against
# dest_name = symbol of the named URL
def redirect_to_url(source_match,dest_name)
param_symbols = source_match.scan(/:([a-z\-\_]+)/i).flatten.map{|i| i.to_sym}
match source_match, :to=>redirect{|params,request|
Rails.application.routes.url_helpers.send("#{dest_name}_path", params.slice(*param_symbols))
}
end
This is achievable, you just have to refer straight to Rails URL helpers module through the lambda version of the redirect since you need this to be lazily resolved:
match "articles/view/:id", redirect {Rails.application.routes.url_helpers.article_path}
Note that this might not work since article_path requires an id to be passed to in order to operate. If this is the case you can use params which are passed to the lambda version of the redirect directive:
match "articles/view/:id", redirect {|params, request| Rails.application.routes.url_helpers.article_path(params[:id]) }
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