有条件地将skip_before_filter应用于:if =>轨道条件4

时间:2013-10-13 13:22:38

标签: ruby-on-rails devise ruby-on-rails-4

我有一个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. 这是否会对性能产生任何影响。如果有,那么还有更好的方法吗?

1 个答案:

答案 0 :(得分:8)

回调中的rails文档(之前,之后,周围的动作)实际上非常糟糕。看到这个类似的问题:skip_before_filter ignores conditionals

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

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

仅通过调用不同的过滤器不会对性能产生影响。性能问题通常来自广泛的数据库查询或其他外部系统调用。

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