skip_before_filter忽略条件

Smu*_*dge 14 ruby-on-rails devise

我只是在应用程序处于生产模式时才尝试使用skip_before_filter.(我不希望我的开发实例公开,我希望应用程序自动检测它所在的实例类型,并在它不处于生产模式时显示登录屏幕).所以,我的应用程序控制器有以下几行:

before_filter :authenticate_user!, :except => "sign_in" #redirects to log-in
Run Code Online (Sandbox Code Playgroud)

并且用于显示页面的控制器具有以下行:

skip_before_filter :authenticate_user!, :only => :show, :if => :in_production
#public pages are public, but only when in production.
Run Code Online (Sandbox Code Playgroud)

而in_production就是:

  def in_production
    ENV['RAILS_ENV']=='production'
  end
Run Code Online (Sandbox Code Playgroud)

我意识到这里可能还有其他途径,但我很好奇为什么skip_before_filter似乎忽略了条件并总是跳过before_filter.有什么我想念的吗?

Ton*_*.io 19

这是一个Rails错误(或至少是一个没有记录的奇怪行为).它在这里被跟踪:https://github.com/rails/rails/issues/9703

在这个帖子中,你可以找到一个(扭曲的)解决方案.

代替

skip_before_filter :authenticate_user!, :only => :show, :if => :in_production
Run Code Online (Sandbox Code Playgroud)

skip_before_filter :authenticate_user!, :only => :show
before_filter      :authenticate_user!, :only => :show, :unless => :in_production
Run Code Online (Sandbox Code Playgroud)

它对我有用.


Raf*_*aez 7

我发现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
Run Code Online (Sandbox Code Playgroud)


Dav*_*ulc 5

我不确定是否skip_before_filter接受:if参数,所以我会尝试这种语法

(skip_before_filter :authenticate_user!, :only => [:show]) if in_production
Run Code Online (Sandbox Code Playgroud)

如果它仍然不起作用,请尝试将其放入您的应用程序控制器中

if ENV['RAILS_ENV']=='production'
  skip_before_filter :authenticate_user!, :only => :show
end
Run Code Online (Sandbox Code Playgroud)