skip_before_filter忽略条件

时间:2011-01-09 01:02:01

标签: ruby-on-rails devise

我正在尝试仅在应用处于生产模式时使用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。有什么我想念的吗?

4 个答案:

答案 0 :(得分:19)

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

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

而不是

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

它对我有用。

答案 1 :(得分:6)

我发现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

答案 2 :(得分:4)

我不确定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

答案 3 :(得分:0)

我就是这样解决这个问题的。

skip_before_filter :authenticate_user!, :if => { action_name == 'show' && in_production }

https://github.com/rails/rails/issues/9703#issuecomment-223574827