【问题标题】:A before_filter does not see value assigned in another before_filter一个 before_filter 看不到在另一个 before_filter 中分配的值
【发布时间】:2014-07-16 10:12:52
【问题描述】:

我正在尝试从另一种方法访问方法中设置的一个变量。这是在下面的 Rails 1.9 代码中。

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :method1
  before_filter :method2
  def method1
    @remote_user = 'dev_user'
  end
  def method2
    unless @remote_user.present?
      render :status => 401, :text => "Authentication failed"
      false
    end
  end

当尝试在第二种方法中访问它时,它总是返回空白。 401 总是返回文本"Authentication failed"。有人可以建议我做错了什么吗?

【问题讨论】:

  • 我不认为是这样,因为如果我在除非语句之前立即添加 @remote_user = 'dev_user' 它不会返回 401 和“身份验证失败”
  • 这是因为@remote_user只在method1初始化,在method2没有初始化。
  • 没有 Rails 1.9 这样的东西。

标签: ruby-on-rails ruby


【解决方案1】:

如果您需要保证在 before_filter 上一个方法在另一个方法之前被调用,请执行以下操作:

before_filter :fn3

def fn3
  fn1
  fn2
end

来自 -> How can I specify the order that before_filters are executed?

希望对你有帮助

已编辑

更好的是,使用 prepend_before_filter 在 before_filter 方法之前解决任何需要解决的问题。

在你的情况下:

    class ApplicationController < ActionController::Base
      protect_from_forgery
      prepend_before_filter :method1
      before_filter :method2
      def method1
        @remote_user = 'dev_user'
      end
      def method2
        unless @remote_user.present?
          render :status => 401, :text => "Authentication failed"
        false
      end
    end

【讨论】:

  • 我刚试过,还是不行。我认为正在调用该方法,它只是没有以某种莫名其妙的方式设置值
【解决方案2】:

为确保before_filter 的顺序正确,您可以使用prepend_before_filterappend_before_filter。 Imho prepend 是默认行为,因此您的过滤器以相反的顺序执行。

所以要解决这个问题,你必须写:

class ApplicationController < ActionController::Base

  before_filter :method2
  prepend_before_filter :method1

您可以只写两次before_filter(按此顺序)就可以了,但恕我直言,这更具表现力。先写下所有顺序无关紧要的before_filters,然后写prepend需要排在第一位的。

你也可以写

class ApplicationController < ActionController::Base

  before_filter :method1
  append_before_filter :method2

完全相同,但确保最后执行 method2。随你喜欢:)

另外请注意,在其他控制器(从 ApplicationController 派生)中定义的过滤器通常会首先执行!

【讨论】:

  • 如果从 ApplicationController 派生的控制器中有一个过滤器正在调用具有不同定义的同名方法,会发生什么?
  • 本地定义覆盖应用控制器中的定义。恕我直言,这意味着应用程序控制器中定义的before_filter 将调用派生控制器中的方法。所以如果派生类中多了一个同名的before_filter,就会被调用两次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
相关资源
最近更新 更多