如何在Rails 5.1上基于用户角色呈现视图

时间:2018-06-19 00:02:01

标签: ruby-on-rails devise

我目前正在开发一个Rails 5.1应用程序,它有两个不同的用户角色:“Admin”和“Customer”。 (我将角色存储在用户表上名为“role”#string的列中)。

我正在寻找基于用户角色呈现不同视图的最有效方法。例如

  • 如果用户使用user.role =“Customer”登录,我想渲染 顾客#索引

  • 如果用户使用user.role =“Admin”登录,我想渲染 管理员#索引

现在路由根是“admin #index”。有没有办法根据当前用户的角色更改根路由?

任何有关根据用户角色呈现不同视图的最有效方法的提示都将受到赞赏!非常感谢你!

1 个答案:

答案 0 :(得分:0)

您可以为资源指定after_sign_in_path_for路由。所以

application_controller.rb

....

def after_sign_in_path_for(resource)
  if resource.role == "Customer"
    customers_path (or whatever the name of the path is in your routes)
  elsif resource.role == "Admin"
    admins_path (same here, whatever the name of the path is in your routes)
  else
    super
  end
end

....

有很多这样的方法,您可能会发现有用的方法,特别是https://www.rubydoc.info/github/plataformatec/devise/Devise/Controllers/Helpers:after_sign_in_path_for或所有选项https://www.rubydoc.info/github/plataformatec/devise/Devise/Controllers/Helpers

相关问题