1

我正在尝试将过滤器添加到基于某个角色(使用 role_requirement)的控制器,然后是每个用户拥有的 company_id。

所以基本上我需要这样的东西:

require_role "company" ** This is working fine
  before_filter :company_required

def company_required
  unless current_user.company_id == Company.find(params[:id])    
end 

结尾

我收到 nil:NilClass 的未定义方法“company_id”的错误

我将不胜感激任何指导。谢谢

4

4 回答 4

2

如果用户未登录,current_user 将为 nil。你将不得不提防这种情况。这里也缺少一些东西。无论过滤器调用的方法返回什么,操作都会继续进行。除了在过滤器中调用渲染或重定向的方法。

这是一个工作过滤器,它可以执行您尝试执行的操作,假设您有一个名为 denied 的命名路由。

require_role "company" ** This is working fine
  before_filter :company_required

def company_required
  redirect_to denied_url unless logged_in? && current_user.company_id == Company.find(params[:id])    
end

您可以通过在默认路由块之前将以下内容添加到 config/routes.rb 来添加路由。如果需要,您可以使用现有控制器或创建新控制器。这是我通常使用的:

map.denied '/denied', :controller => "home", :action => "denied"

正如其他人所说,您似乎正在使用 Restful 身份验证。您可能会发现查看文档有助于更好地了解登录过程。简短的版本是用户将向设置 current_user 的 session_controller 提交一个将他们标识为应用程序成员的表单。如果你运行了生成器,你应该访问上面提到的logged_in?方法。

session_controller 和 current_user 在您的应用程序中可能有所不同,因为您给了 Restful Authentication generator 不同的参数。

于 2009-10-10T09:41:51.777 回答
0

我假设您正在使用 RESTful 身份验证,因为您正在引用“current_user”,并且看起来没有定义。

在查看该插件的代码时,它看起来像是在 AuthenticatedSystem 模块中设置的。我的猜测是您没有将其包含在控制器中。

根据为会话控制器自动生成的代码,您应该将“include AuthenticatedSystem”添加到您的应用程序控制器(因此它对所有控制器都可用)。

这是来自 RESTful 身份验证生成的会话控制器的代码块。

# This controller handles the login/logout function of the site.  
class SessionsController < ApplicationController
  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem  
于 2009-09-18T01:54:27.937 回答
0

在不知道错误的情况下,几乎无法诊断。以下是一些建议:

require_role "company" # This is working fine

then before_filter :company_required
def company_required
  unless current_user.company_id == params[:id].to_i #cast to int, to be sure
  redirect_to ('/')
end

此外,请确保您设置了 before_filter 以实际获取 current_user,否则您可能会收到如下错误:

尝试获取 nil.company_id 时出错

如果这是错误,那么 current_user 为 nil,可能是因为它从未设置过。

于 2009-09-16T15:55:48.677 回答
0

我会尝试几件事:

  • unless current_user.company == Company.find(params[:id]). 注意我在 current_user 对象上调用公司,而不是 company_id。此外,params 是一个哈希,因此您需要通过 [] 访问它。
  • 除非 current_user.company_id = params[:id]>/code>。可以说这更好,因为我们没有向数据库发出请求以查找 Company 实例。
  • 如果这些都不起作用,请尝试使用 ruby​​-debugger 查看在每个点返回和评估的内容。
于 2009-09-16T15:43:19.047 回答