Rails - 基于路由名称的路由重定向

Sya*_*ien 1 ruby routes ruby-on-rails

目前,如果我想重定向到某个页面,我必须使用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'
Run Code Online (Sandbox Code Playgroud)

Xer*_*ero 5

您可以使用 url 路径进行重定向,但不能使用路由名称进行重定向。

get '/house-url', to: redirect('/home-url')
Run Code Online (Sandbox Code Playgroud)

将任意路径重定向到另一条路径

https://guides.rubyonrails.org/routing.html#redirection

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

编辑

我找到了更好的方法:

1. 创建重定向到主页

创建一个名为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
end
Run Code Online (Sandbox Code Playgroud)

2.编辑你的route.rb

并将 RedirectToHome 添加到您要重定向的路线

  get '/home-url', to: 'home_ctrl#show', as: 'home'
  get '/house-url' => redirect(RedirectToHome.new)
Run Code Online (Sandbox Code Playgroud)