【问题标题】:Rails - route redirect based on Route NameRails - 基于路由名称的路由重定向
【发布时间】:2019-02-20 08:36:47
【问题描述】:

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

【问题讨论】:

  • 我发布了一个答案,但如果有人找到其他方式,我会很感兴趣

标签: ruby-on-rails ruby routes


【解决方案1】:

您可以使用 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
end

2。编辑您的路线.rb

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

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

【讨论】:

  • 所以没有办法重定向到另一个路径(基于路由名称)??
  • @SyamsoulAzrien 我找到了更好的方法,请检查我的编辑。使用 RedirectToHome 它可以工作。如果对您有用,请随时接受我的回答=)
  • 看起来很复杂..但我认为除此之外别无他法...而且它确实有效...感谢您的回答...
  • 我同意,这有点样板
【解决方案2】:

如果我正确阅读了您的问题,您是否希望将请求的路由传递给重定向?

你可以这样做:

get '/houses/:house_id', to: redirect { |path_params, req| "/houses/#{path_params[:house_id]}" }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 2019-01-23
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    相关资源
    最近更新 更多