目前,如果我想重定向到某个页面,我必须使用to: redirect('/this-is-some-url') ..
我想知道是否可以使用Route Name (如to: redirect('route_name') )重定向到某个页面
我尝试了下面的代码,但它不起作用:
get '/house-url', to: redirect('home') #the value is route name
get '/home-url', to: 'home_ctrl#show', as: 'home'发布于 2019-02-20 08:50:05
您可以使用url路径重定向,但不能使用路由的名称。
get '/house-url', to: redirect('/home-url')将任何路径重定向到另一条路径
https://guides.rubyonrails.org/routing.html#redirection
https://api.rubyonrails.org/classes/ActionDispatch/Routing/Redirection.html
编辑
我找到了更好的方法:
1.创建RedirectToHome
创建一个名为RedirectToHome的类(在redirect_to_home.rb文件中)。
您可以在app/controllers/中创建此示例
class RedirectToHome
def call(params, request)
Rails.application.routes.url_helpers.home_path # this is the path where to redirect
end
end2.编辑route.rb
并将RedirectToHome添加到要重定向的路由中。
get '/home-url', to: 'home_ctrl#show', as: 'home'
get '/house-url' => redirect(RedirectToHome.new)发布于 2019-02-20 09:42:04
所以,如果我正确地读到了你的问题,你想把请求的路线转到重定向吗?
你可以这样做:
get '/houses/:house_id', to: redirect { |path_params, req| "/houses/#{path_params[:house_id]}" }https://stackoverflow.com/questions/54781981
复制相似问题