skip_before_filter忽略条件
我只是在应用程序处于生产模式时才尝试使用skip_before_filter。 (我不希望我的开发实例公开,我希望应用程序自动检测它所在的实例类型,并在它不处于生产模式时显示登录屏幕)。 所以,我的应用程序控制器有以下几行:
before_filter :authenticate_user!, :except => "sign_in" #redirects to log-in
并且用于显示页面的控制器具有以下行:
skip_before_filter :authenticate_user!, :only => :show, :if => :in_production #public pages are public, but only when in production.
而in_production就是:
def in_production ENV['RAILS_ENV']=='production' end
我意识到这里可能还有其他途径,但我很好奇为什么skip_before_filter似乎忽略了条件并总是跳过before_filter。 有什么我想念的吗?
这是一个Rails错误(或至少是一个无证的奇怪行为)。 它在这里被跟踪: https : //github.com/rails/rails/issues/9703
在这个post中,你可以找到一个(扭曲的)解决方案。
代替
skip_before_filter :authenticate_user!, :only => :show, :if => :in_production
写
skip_before_filter :authenticate_user!, :only => :show before_filter :authenticate_user!, :only => :show, :unless => :in_production
它对我有用。
我发现SmartLove在所描述的场景中发布的解决方案存在一种安全漏洞或意外行为。 这条线
before_filter :authenticate_user!, :only => :show, :unless => :in_production
因为:only => :show
,它会覆盖 ApplicationController中定义的现有before_filter。 这意味着该控制器的所有操作(例如:edit,:create等),除了:show one,将省略authenticate_user! 过滤。
一种可能的解决方案是删除:only子句并检查条件方法内部调用的操作。 例如:
before_filter :authenticate_user!, :unless => :skip_filter? def skip_filter? params[:action] == "show" && in_production end
我不确定skip_before_filter
接受:if
参数,所以我会尝试这种语法
(skip_before_filter :authenticate_user!, :only => [:show]) if in_production
如果仍然无效,请尝试将其放入应用程序控制器中
if ENV['RAILS_ENV']=='production' skip_before_filter :authenticate_user!, :only => :show end