1

我正在尝试使用仪表板控制器中的设计阻止用户、管理员、代理 - 我收到此错误:

DashboardController:Class 的未定义局部变量或方法“current_admin”

class DashboardController < ApplicationController
  if current_admin.present?
    before_filter :blocked_admin?
  elsif current_agent.present?
    before_filter :blocked_agent?
  elsif current_user.present?
    before_filter :blocked_user?
  end

  def blocked_admin?
    if current_admin.present? && current_admin.blocked_admin?
      sign_out current_admin
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    end
  end

  def blocked_agent?
    if current_agent.present? && current_agent.blocked_agent?
      sign_out current_agent
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    end
  end

  def blocked_user?
    if current_user.present? && current_user.blocked_user?
      sign_out current_user
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    end
  end

end

我是 Rails 新手,优化(DRY)代码的最佳方法是什么。并解决我上面提到的错误。

我也尝试这样做,我以不同的方式将它放在“应用程序控制器”中。我在删除此行之前遇到的错误:

redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"

在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。另请注意,重定向和渲染都不会终止操作的执行,因此如果您想在重定向后退出操作,则需要执行“redirect_to(...) and return”之类的操作。

删除此行后

redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"

TrueClass:Class 的未定义方法“model_name”

  def after_sign_in_path_for(resource)
    if resource.is_a?(Admin) && resource.blocked_admin?
      sign_out current_admin
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    elsif resource.is_a?(Agent) && resource.blocked_agent?
      sign_out current_agent
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    elsif resource.is_a?(Agent) && resource.blocked_agent?
      sign_out current_user
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    else
      #super
      "/dashboard"
    end
  end
4

2 回答 2

2

我建议您考虑使用像cancan这样的外部 gem进行身份验证。有非常有用的文档/截屏视频可用。如果您认为它不适合您的需要,您可以随时在此处查看可用的工具。您也可以尝试执行以下操作:

在您的 application_controller.rb 中:

before_filter :check_for_blocking

def check_for_blocking
  if current_user.blocked?
    sign_out current_user
    redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
  end
end

您将面临的主要问题是将 current_admin、current_agent 统一为 current_user。您需要角色管理 - cancan 或其他类似的角色身份验证 gem 提供。

于 2012-10-06T14:10:39.480 回答
0

尝试添加这三行

before_filter :authenticate_user!
before_filter :authenticate_admin!
before_filter :authenticate_agent!
于 2012-10-07T10:44:40.403 回答