Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 routes redirect to named url without hitting controller

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
like image 367
spyle Avatar asked Nov 23 '25 07:11

spyle


1 Answers

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]) }
like image 57
Erez Rabih Avatar answered Nov 24 '25 21:11

Erez Rabih