0

我试图弄清楚在用户登录到 Ruby/Rails3 应用程序后,如何根据他们的角色在特定 URL 上重定向用户。

到目前为止,我使用 authlogic gem 进行身份验证,使用 cancan gem 进行角色设置。

角色就像这样(在 app/models/user.rb 中定义):

class User < ActiveRecord::Base
  acts_as_authentic
  ROLES = %w[admin customer demo]
end

现在有 app/controllers/user_session_controller.rb 负责登录。我想做这样的事情:

for r in User.role
      if r == "admin"
        redirect_to admins_url
      else
        redirect_to users_url
      end
end

由于以下错误,这不起作用:

"undefined method `role' for #<Class:0xb5bb6e88>"

有没有一种简单或优雅的方法可以根据用户的角色将用户重定向到特定的 URL?

(角色在用户表的 mysql 列“角色”中定义。)

4

2 回答 2

1

你一定要看看CanCan。这是管理用户角色和能力的一种非常合乎逻辑的方式。

于 2011-02-08T01:58:21.147 回答
1

令人for r in User.role困惑。您是要访问在类上定义的 ROLES 数组还是要访问当前用户的角色值?

如果您尝试访问 ROLES 数组,请使用User::ROLES.

使用 authlogic,通常在 application_controller 中定义 current_user。因此可以使用找到当前用户的角色current_user.role

所以你的代码可能看起来像

  if current_user.role == "admin"
    redirect_to admins_url
  else
    redirect_to users_url
  end
于 2011-02-08T01:52:22.283 回答