【问题标题】:ActionController::RoutingError (undefined method `before_filter' for Class): ErrorActionController::RoutingError(类的未定义方法“before_filter”):错误
【发布时间】:2012-03-23 16:55:19
【问题描述】:

基本上我有一个 UsersInitializeController 类

class UsersInitializeController < ApplicationController
  before_filter :authenticate_user!

  def create
    render true
  end
end

验证用户!在应用程序控制器中找到

class ApplicationController < ActionController::Base
  # protect_from_forgery

  def authenticate_user!
    @current_user = User.find_by_token params[:auth_token]
    if !@current_user
      @current_user = User.create :token => params[:auth_token]
    end
  end

end

当我的应用程序启动时,它会向 UsersInitializeController 发送 POST 请求。由于设置了 before_filter,因此它将调用 authenticate_user!第一的。但是我得到的错误说 before_filter 是一个未定义的方法。

据我所知,before_filter 存在于 ActionController 中,并且由于 UsersInitializeContoller

异常堆栈(根据要求)

Started POST "/users_initialize.json" for 127.0.0.1 at 2012-03-06 00:32:50 -0800

ActionController::RoutingError (undefined method `before_filter' for UsersInitializeController:Class):
app/controllers/users_initialize_controller.rb:3:in `<class:UsersInitializeController>'
app/controllers/users_initialize_controller.rb:1:in `<top (required)>'

Routes.rb 文件(根据要求)

MyApplication::Application.routes.draw do
 resources :users_initialize
 match 'info/required_client_version' => 'info#required_client_version'
end

###问题已解决###

未使用的 Devise Gem 不知何故导致了并发症。删除它并完成。

【问题讨论】:

  • 你能发布整个异常堆栈吗?查看您在标题中使用的错误,我认为问题不在于您的 authenticate_user 方法。这是一个路由错误,未定义的方法是 before_filter。
  • 很奇怪。它表明在 Rails 加载之前调用了 before_filter 方法。如果将 before_filter 移动到应用程序控制器并执行相同的操作会发生什么?
  • 另外,相关帮助文件的名称是什么,它定义了什么类?
  • 请同时发布您的routes.rb 文件的内容。
  • @RobinFisher 即使我将 before_filter 移动到应用程序控制器,我也会遇到同样的问题。不确定我是否理解您的问题

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

无法重现,您发布的代码在我的 Rails 3.2.2 应用上运行良好。

您的源文件可能有问题(即某处有一些额外的隐藏字节)。

您可以尝试逐步解决此问题:

  1. 添加新的UsersController 并将resources :users 添加到routes.rb
  2. 使用以下代码添加index 操作:

    def index 
        render :text => "Hello there"
    end
    
  3. 当您访问http://localhost:3000 时,您应该会看到文本“Hello there”

  4. 添加before_filter 并通过添加例如验证过滤器已执行。 logger.warn( 'In the Filter' ) 到过滤方法的开头

【讨论】:

  • 有用的文字,但最好用作评论。 “我无法重现您的问题”不是答案。
【解决方案2】:

在“included do”块中添加 before_filter:

included do
    before_filter :authenticate_user!
end

更新: 刚刚注意到你已经解决了。但是我遇到了同样的麻烦,上面的解决方案在我的情况下解决了它。所以,我会在这里留下评论,因为它可能会帮助其他人

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2016-10-26
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多