在 Rails 条路线中重定向

Redirecting in Rails routes

我在我的 rails 应用程序中简单地路由如下所示:

  resources :users, only: :show

例如,现在我想重定向到 http://no_present_path.com when user with sended id is not present and when user with seneded id is present redirect to http://present_path.com。有没有办法用路由约束来做到这一点?

路由是表示 url 的一部分的字符串与控制器中的方法和操作之间的简单匹配。实现目标的最佳方法是在控制器中使用 before_action。例子

class UsersController < ApplicationController
  before_action :authenticate_user, only: [:show]

  def show
    ...
  end

  private

  def authenticate_user
    redirect_to some_other_path unless id_correct?
  end
end