我有一个 Rails 应用程序,它使用名为:Competitions
的引擎。当我启动 Rails 服务器并第一次加载页面时,它显示:
LoadError:无法自动加载常量锦标赛,需要/home/stein/RubyProjects/my_app/engines/competitions/app/models/competitions/tournament.rb 来定义它
Rails 似乎不知道文件中有 Competitions::Tournament
类,它只查找 Tournament
。如何让 Rails 搜索 Competitions::Tournament
而不是 Tournament
?
Ruby 版本:2.1.1
Rails 版本:4.1.0
操作系统:Ubuntu 14.04 LTS
最佳答案
我使用相同版本的 Ruby/Rails,并且我还有一个带有自动加载模型的引擎。您是否在定义 Engine Gem 的模块中定义了模型?即:
假设您的引擎名为“竞赛”:
module Competitions
class Tournament < ActiveRecord::Base
end
end
您还可以将模块内联放置:
class Competitions::Tournament < ActiveRecord::Base
end
这是因为 Rails 在文件系统的层次结构中查找模块/类,因此如果您在 app/models/competitions/another_namespace/tournament.rb
中有一个类,那么您必须将您的模型包装在由目录 competitions
和 another_namespace
命名的模块中,作为 Competitions::AnotherNamespace::Tournament
。
尝试一下并重新启动您的虚拟或主机应用程序。
关于ruby-on-rails - Rails 引擎不自动加载带有命名空间的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23570059/