Rails' routes: how to pass “all” request param

2019-01-17 20:34发布

问题:

I want to redirect all root requests to a /pages/home url, but I want to keep all the params used in the original request.

So:

http://myserver.com/?param1=value1&param2=value2

Becomes

http://myserver.com/pages/home?param1=value1&param2=value2

There are several SO questions about passing params in a redirect but I haven't found any related to passing request's params.

回答1:

# routes.rb
root :to => redirect { |params, request| "/pages/home?#{request.params.to_query}" }

Update 1

You can also play with the request.params to build the new path:

root :to => redirect { |params, request| "/pages/#{request.params[:page]}.html?#{request.params.to_query}" }


回答2:

The other answer works but leaves a ? at the end in case there are no parameters.

This seems to do the trick without the side effects:

root to: redirect(path: '/quick_searches/new')

Hope it helps!



回答3:

In Rails 5, this can be now be done concisely simply by rewriting ONLY the path component in the redirect (so all original query params will be retained):

# in routes.rb
root to: redirect(path: '/pages/home')

Relevant documentation link:

http://api.rubyonrails.org/classes/ActionDispatch/Routing/Redirection.html



回答4:

Building on @fguillen's answer for Rails4

You need two lines in routes.rb

# in routes.rb
match "/pages/home", to: 'pages#index', via: :get    
match "/", to: redirect{ |params, request| [ "/pages/home", request.env["rack.request.query_string"] ].join("?") }, via: :all

The join on an array also handles the dangling question mark at the end in case there are no parameters.