如何查看 Rails 中 routes.rb 的用户管理员?

How can I check user admin on routes.rb in Rails?

我在 Rails 应用程序中有两个不同的视图和两个不同的控制器,我希望用户根据用户是否是管理员重定向到特定的视图。

我看到 SO post 喜欢 this one 它根据用户是否经过身份验证来引导页面,但我正在寻找这样的东西(我正在使用设计):

#routes.rb
  authenticated :user do
    if user.admin
      root to: "admin/first_page#index", as: :authenticated_root
    else
      root to "first_page#index", as: :authenticated_root
    end
  end

  root to: "user/sign_in"

当用户登录时,它会检查用户的管理员权限。如果用户是管理员,请转到 admin/first_page#index。如果用户不是管理员,请转至 first_page#index.

我想过只使用一个页面并为非管理员隐藏某些功能,例如:<% if user.admin%><%= secret_admin_feature %><% end %> 保持干燥,但我有自己的原因为什么我选择不保持干燥案件。

是否可以从 routes.rb 进行管理员检查?如果是,怎么办?如果没有,什么是好的选择?

我认为检查路由中的管理员权限不是一个好主意。正确的做法如下:

  • 您将有一个名为 is_admin?application_helper 方法来检查用户是否是管理员。

  • 您将通过某种方式提交您的登录表单。这就是您需要使用助手和重定向的地方。

def sign_in
  # submit form and do your stuff here
  # and if your form submission was successful you would do something like this:    
  redirect_to admin_first_page_index_path and return if is_admin?
  redirect_to first_page_index_path and return
end

我就是这样做的。

如果表单提交失败,您仍然需要提供登录页面的重定向。在 admin/first_page#index 方法中,您可能想要检查用户是否是管理员并重定向到另一个页面,只是为了强制非管理员用户返回他们的流程。