这里可能有数百个这样的问题,但我还没有找到一个。我使用的是 Rails 6,但在编写自定义模块时总是遇到问题。
我有一个用于创建电子邮件令牌的文件:lib/account_management/email_token.rb
module AccountManagement
module EmailToken
def create_email_token(user)
....
end
end
end
然后在我的控制器中,我尝试了各种方法:
require 'account_management/email_token'
include AccountManagement::EmailToken
调用它: create_and_send_email_token(user)
有一次我添加了 config.eager_load_paths << Rails.root.join('lib/account_management/')
,但我认为您仍然不必这样做。
每当我尝试调用控制器操作时,我都会收到以下错误消息之一:
*** NameError Exception: uninitialized constant Accounts::SessionsController::EmailToken
#this happens if I try to manually send through the rails console
(although inside of a byebug I can call require 'account_management/email_token' and it returns
true.
最常见的是:
NoMethodError (undefined method `create_email_token' for #<Accounts::SessionsController:0x00007ffe8dea21d8>
Did you mean? create_email):
# this is the name of the controller method and is unrleated.
答案 0 :(得分:2)
解决此问题的最简单方法是将您的文件放在 app/lib/account_management/email_token.rb
中。 Rails 已经自动加载应用文件夹的任何子目录*。
/lib
从 Rails 3 开始就没有出现在自动加载路径上。如果你想把它添加到自动加载路径中,你需要在自动加载/急切加载中添加 /lib
而不是 /lib/account_management
路径。在 Zeitwerk 术语中,这添加了一个根,Zeitwerk 将从中索引和解析常量。
config.autoload_paths += config.root.join('lib')
config.eager_load_paths += config.root.join('lib')
请注意,eager_load_paths 仅在开启急切加载时使用。它在开发中默认关闭以启用代码重新加载。
/lib
已添加到 $LOAD_PATH
中,因此您还可以通过以下方式手动要求该文件:
require 'account_management/email_token'
见: