【问题标题】:Skip before_filter in Rails在 Rails 中跳过 before_filter
【发布时间】:2011-01-24 07:31:56
【问题描述】:

为清楚起见,名称和对象已被简化。基本概念保持不变。

我有三个控制器:dogcathorse。 这些控制器都继承自控制器animal。 在控制器animal 中,我有一个前置过滤器,用于对用户进行身份验证:

before_filter :authenticate

def authenticate
  authenticate_or_request_with_http_basic do |name, password|
    name == "foo" && password == "bar"
  end
end

dogshow 操作中,我需要对所有用户开放访问(跳过身份验证)。

如果我要单独为dog 编写身份验证,我可以这样做:

before_filter :authenticate, :except => :show

但由于dog 继承自animal,我无法访问特定于控制器的操作。在animal 控制器中添加:except => :show 不仅会跳过dogshow 操作的身份验证,还会跳过cathorse 的身份验证。这种行为是不希望的。

我怎样才能只为dogshow 操作跳过身份验证,同时仍然从animal 继承?

【问题讨论】:

    标签: ruby-on-rails inheritance before-filter


    【解决方案1】:

    只是一个使用 rails 4 的小更新,现在是 skip_before_action :authenticate, :only => :show,而 before_filters 现在应该使用 before_action

    【讨论】:

    • 这应该是一条评论。
    【解决方案2】:
    class Dog < Animal
      skip_before_filter :authenticate, :only => :show
    end
    

    有关过滤器和继承的更多信息,请参阅ActionController::Filters::ClassMethods

    【讨论】:

    【解决方案3】:

    给出的两个答案都对了一半。为了避免打开所有的狗动作,您需要将 skip_before_filter 限定为仅适用于“显示”动作,如下所示:

    class Dog < Animal
      skip_before_filter :authenticate, :only => :show
    end
    

    【讨论】:

      【解决方案4】:

      为此,您可以使用 skip_before_filter

      Rails API中有解释

      在您的示例中,dogjust 必须包含

      skip_before_filter :authenticate
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多