0

鉴于如何将 before_filter 用于单个用户分类已有详细记录,因此我在为多种用户类型获得操作级保护时遇到了麻烦。让我解释:

我有这样的东西...

class ApplicationController < ActionController::Base
  class << self 
    attr_accessor :standard_actions
  end
  @standard_actions = [:index, :show, :new, :edit, :create, :update, :destroy]

  def require_guardian
    unless current_user and current_user.is_a?(Guardian)
      store_location
      redirect_to home_url
      return false
    end
  end

  def require_admin
    unless current_user and current_user.is_a?(Administrator)
      store_location
      redirect_to register_url
      return false
    end
  end
end

在 GuardiansController 中,我只想允许管理员的标准操作,但所有其他操作都应该需要 Guardian。所以我尝试了这个...

class GuardiansController < ApplicationController
  before_filter :require_admin, :only => ApplicationController::standard_actions
  before_filter :require_guardian, :except => ApplicationController::standard_actions
  ...
end

最终进行递归重定向。一定会有更好的办法?

4

1 回答 1

0

好吧,这又是一个不仔细看,漏掉东西的情况。我无意中设置了以递归方式重定向用户的路由。当您正确设置路由时,上述解决方案工作得很好:

def require_guardian
  unless current_user and current_user.is_a?(Guardian)
    store_location
    # this route (home_url) sent the user to another controller which ran a before_filter sending them back here again.
    # redirect_to home_url 
    # So I changed it to a neutral route and it works great!
    redirect_to register_url
    return false
  end
end
于 2010-02-13T00:31:25.823 回答