【问题标题】:before_filter in ApplicationController not called (Rails 4)未调用 ApplicationController 中的 before_filter (Rails 4)
【发布时间】:2015-08-30 09:44:23
【问题描述】:

我想在我的 rails 应用程序的每个控制器的每个操作之前调用一个过滤器。

为了实现这一点,我只是在我的 ApplicationController 中使用了before_filter

但是,它不起作用,当我收到有效请求时,我的方法永远不会被调用。

这是我的 ApplicationController 的内容:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_filter :authenticate_with_token

  def authenticate_with_token
      begin
          auth = AuthenticatorService.new
          auth.authenticate params[:email], params[:token], request.method, request.fullpath
          @current_user = auth.user
          return true
      rescue Exception => e
          return false
      end
  end

end

即使在 rails 4 中不应该弃用 before_filter,我也尝试使用 before_action,但结果保持不变。

有什么办法吗?

【问题讨论】:

  • 确保所有其他控制器都继承自应用程序控制器:OtherController &lt; ApplicationController 还要确保它确实没有进入函数、日志记录或其他内容
  • 就是这样...我继承自 ActionController::Base 而不是 ApplicationController。谢谢!
  • 你可以使用 before_action 代替 before_filter

标签: ruby-on-rails ruby-on-rails-4 controller before-filter


【解决方案1】:

//编辑: grml。我看到你已经解决了你的问题。

class ApplicationController < ActionController::Base
  before_filter :throw_up
  before_filter {
    raise "hi friend"
  end
  private
    def throw_up
      raise "i need to puke"
   end
end

class PagesController < ApplicationController
    def index
    end
end

如果我调用索引操作 - 它工作得很好。 它正在引发“我需要呕吐”。

请帮我一个忙:如果您编写由过滤器调用的方法,它们应该是私有的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    相关资源
    最近更新 更多