有条件地应用 skip_before_filter 在轨道 4 中使用 :if => 条件



我有一个Events控制器,如果事件是公开的,我想跳过身份验证。

在我的ApplicationController中,我有这个呼吁来设计authenticate_user!

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
end

现在,在我的事件表中,我有一个名为 public 的布尔字段。我用它来检查事件是否公开。就像EventsController这样的

class EventsController < ApplicationController
  skip_before_action :authenticate_user!, only: :show, if: Proc.new { :is_public? }
end

但出于某种原因,这不起作用。 所以我不得不这样做:

class EventsController < ApplicationController
  skip_before_action :authenticate_user!, only: :show
  before_action :authenticate_user!, unless: :is_public?
  def is_public?
    @event.present? && @event.is_public
  end
end

这按预期工作,如果@event.public = true,请跳过身份验证,因为上述操作在跳过后会以相反的条件重复before_filter

我想知道:

  1. 我做的是对的吗?
  2. 这是否会对性能产生影响。如果是,那么有没有更好的方法?

关于回调(之前、之后、围绕操作)的 Rails 文档实际上非常糟糕。 请参阅类似的问题: skip_before_filter忽略条件语句

所以我总是参考导轨指南。 您感兴趣的部分在这里: http://guides.rubyonrails.org/action_controller_overview.html#other-ways-to-use-filters

我不完全确定这也适用于跳过过滤器,但值得一试。

不应仅通过调用不同的筛选器来影响性能。 性能问题通常来自大量的数据库查询或其他外部系统调用。

我在这里主要担心的是,很难理解为什么有这么多before_action的事情发生......

最新更新