有条件地将skip_before_filter应用于:如果=>条件在rails 4中

我有一个Events控制器,我想要跳过身份validation,因为事件是公开的。

在我的ApplicationController我调用了devise的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这可以按预期工作并跳过身份validation,因为上面的内容在跳过后重复带有反向条件的before_filter

我想知道:

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

回调中的rails文档(之前,之后,围绕操作)实际上非常糟糕。 看到这个类似的问题: skip_before_filter忽略条件

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

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

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

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