0

所以,这是我的问题。我目前正在为 Rails 站点构建一个简单的身份验证系统。为此,我有 3 个类:Person、Session 和 Role。在我的 Person 模型中,我已经定义method_missing为根据本指南动态捕获角色。

在我的 application_controller 中,我有一些逻辑来处理登录和注销,其结果通过以下方式为我提供了当前登录的用户: 当前会话@user = @application_session.person 在哪里@application_session

现在在我的一个控制器中,我不希望任何人能够做任何事情,除非他们是管理员,所以我包括: before_filter @user.is_an_admin?

NoMethodError即使我method_missing在我的模型中定义了,这也会引发 a 。我尝试定义is_an_admin?,让它总是作为测试返回 true ,这很有效。

根据this question,我认为问题可能与代理关联有关。当我运行时: puts @user.proxy_owner 我得到一个会话对象,因为每个用户(Person)可以有很多会话,并且我从当前会话中获取了我的用户(Person)。

我很困惑为什么@user.is_an_admin?不在我的 Person 控制器中调用 method_missing 方法。如果您需要更多信息或代码片段,请告诉我。

我在 Ruby 1.9 上使用 Rails 3

4

3 回答 3

0

I have solved this by moving the method_missing method to my application_controller.rb. I change the logic of the method a little to check for a user, and if found, dynamically check the role. If things were not kosher, I had the method redirect to root_url or return true if the user matched the requested roles.

Finally, in my reports controller, I used before_filter :is_an_admin? and got my desired results. However, I am still unclear as to why method_missing had to be defined in my application controller as opposed to directly in the Person (aka @user) model?

于 2011-05-18T15:39:20.037 回答
0

对于此类任务,我认为 method_missing 是一种过度杀伤力。

现在,如果你有 Session 类,它属于 User,那么你可以拥有这个:


class Session
  belongs_to :user, :extend => PermissionMixin
end

class User
  include PermissionMixin
end

module PermissionMixin
  def admin?
    if cond
      true
    else
     false
    end
  end
end

PS Check cancan,也许它会更好地满足您的需求。

于 2011-05-17T21:57:06.917 回答
0

我在我的系统中使用类似的权限检查来检查用户 > 角色 > 权限关联: User.current_user.can_sysadmin?

在我的控制器中,我必须改用: User.current_user.send('can_sysadmin?')

这也可能对您有用。

于 2011-06-09T16:33:47.983 回答