Ruby-on-rails 模块的 Rails 4 未初始化常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17007685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:08:28  来源:igfitidea点击:

Rails 4 uninitialized constant for module

ruby-on-rails

提问by markhorrocks

In a new rails 4 app I anm getting an unintialized constant error for a module. The module is named ProcessBill and is located in lib/process_bill.rb

在一个新的 rails 4 应用程序中,我收到一个模块的未初始化常量错误。该模块名为 ProcessBill,位于 lib/process_bill.rb

console error:

控制台错误:

ActionController::RoutingError (uninitialized constant BillsController::ProcessBill):

controller code:

控制器代码:

class BillsController < ApplicationController

  include ProcessBill

lib/process_bill.rb

库/process_bill.rb

module ProcessBill

回答by sevenseacat

Have you added lib to your autoload path? This was necessary in Rails 3, I'm not sure if it's still required for Rails 4.

您是否将 lib 添加到您的自动加载路径?这在 Rails 3 中是必需的,我不确定 Rails 4 是否仍然需要它。

Try adding this into the class definition in config/application.rb-

尝试将其添加到类定义中config/application.rb-

    config.autoload_paths += %W(#{config.root}/lib)

回答by Peter Marklund

I had this problem too with the lib directory with Rails 5 and it appeared in production but not in development. To fix it you need to add the lib directory to eager_load_paths. Here is the relevant part from my application.rb:

我在 Rails 5 的 lib 目录中也遇到了这个问题,它出现在生产中,但没有出现在开发中。要修复它,您需要将 lib 目录添加到eager_load_paths。这是我的 application.rb 中的相关部分:

config.autoload_paths << "#{Rails.root}/lib"
config.eager_load_paths << "#{Rails.root}/lib"

回答by Wouter Schoofs

This will also work in Rails 5 in your application.rb file:

这也适用于您的 application.rb 文件中的 Rails 5:

    config.autoload_paths << Rails.root.join('lib')
    config.autoload_paths << Rails.root.join('lib/notifier')

回答by Alyssa Ross

Try adding this line to the top of your controller:

尝试将此行添加到控制器的顶部:

require "#{Rails.root}/lib/process_bill.rb"