Rails 4.0.0应用程序中ActiveSupport的未定义方法“all”

我是开发rails应用程序的新手,所以在大多数情况下,我只依靠rails generate命令来为整个应用程序制作支架。 虽然我的应用程序的每个其他部分都可以正常工作,但这个部分在自动生成后会立即引发错误。

错误如下:

NoMethodError in ConfigurationsController#index undefined method `all' for ActiveSupport::Configurable::Configuration:Class 

这是包含所述无方法调用的代码片段

 def index @configurations = Configuration.all end 

这是所述模型

 class Configuration < ActiveRecord::Base belongs_to :users, class_name: 'User', foreign_key: 'user_id' end 

我添加了belongs_to部分…无论如何,当我通过http://localhost.localhost:3000 / users / 1 / configurations /运行它时,会弹出错误! (是的,我使用嵌套路线)

所以我点击rails控制台来检查Configuration.all返回什么,然后看看

 2.0.0-p247 :004 > Configuration.all Configuration Load (0.3ms) SELECT "configurations".* FROM "configurations" => #<ActiveRecord::Relation [#]> 

我有点迷失为什么该方法在rails控制台中工作然后在浏览器的html视图中失败。 我做错什么了吗?

另外,这是webrick的输出,以防有人找到它

 Started GET "/users/1/configurations/" for 192.168.1.105 at 2013-08-08 10:24:59 +0800 Processing by ConfigurationsController#index as HTML Parameters: {"user_id"=>"1"} Completed 500 Internal Server Error in 1ms NoMethodError (undefined method `all' for ActiveSupport::Configurable::Configuration:Class): app/controllers/configurations_controller.rb:8:in `index' 

不幸的是,您创建了一个类,其名称也是Rails API的一部分(尽管在不同的命名空间中)。 您的类恰好位于顶级命名空间,而Rails类嵌套在ActiveSupport::Configurable命名空间中。 引用Configuration时实际获得的类取决于引用代码的位置。

要指定您希望该类位于顶级命名空间,您可以将您的类称为::Configuration

这是一个简化的测试,用于演示正在发生的事情:

 # Let's say this module & class is defined by a library (eg Rails) module Configurable # analogous to ActiveSupport::Configurable class Configuration # analogous to ActiveSupport::Configurable::Configuration end end class ControllerBase # analogous to ActionController::Base # ActionController::Base includes ActiveSupport::Configurable. # You can confirm this in Rails 4 that this returns true: # ActionController::Base.included_modules.include? ActiveSupport::Configurable include Configurable end # This is your class and constant class Configuration end class MyController < ControllerBase # This is analogous to code inside your Controller. # Inheriting gives you access to the constants in the parent def wrong_class Configuration # oops, we wanted the top-level end def correct_class ::Configuration end end # top-level scope p(top_level_access: Configuration.name) # 'Configuration' p(nested_access: MyController.new.wrong_class.name) # 'Configurable::Configuration' p(scoped_nested_access: MyController.new.correct_class.name) # 'Configuration' 

编辑 - 回复@ maru的评论:

在大多数情况下,您只需使用Configuration.name来获取类的完全命名空间名称。 在控制台试试这个。

如果您在控制器中尝试Rails.logger.info(Configuration.name) ,您可能会在日志中看到ActiveSupport::Configurable::Configuration