Ruby-on-rails 包含模块时出现“未初始化的常量”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11525350/
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-03 03:42:21  来源:igfitidea点击:

"Uninitialized constant" error when including a module

ruby-on-railsrubyruby-on-rails-3.1

提问by Coderama

I am trying to reference an association extension but it errors with:

我正在尝试引用关联扩展,但它出现以下错误:

NameError (uninitialized constant User::ListerExtension):
  app/models/user.rb:2:in `<class:User>'

Here is my implementation:

这是我的实现:

app/models/user.rb

应用程序/模型/user.rb

class User < ActiveRecord::Base
  include ListerExtension

  has_and_belongs_to_many :roles, :uniq => true, :extend => Lister

lib/lister.rb

库/lister.rb

module ListerExtension
  def lister
    self.map(&:to_s).join(', ')
  end
end

I am using Rails v3.1.3.

我正在使用 Rails v3.1.3。

回答by Xavier Holt

Andrew Marshall has an excellent point about the auto-load setup (see the question he links for more on that), but also: Because you named your class ListerExtension, Rails will be looking for a file named lister_extension.rb- notlister.rb. It's smart, but it's not that smart.

安德鲁·马歇尔对自动加载设置一个很好的点(看他的条链路上的问题),也:因为你命名你的类ListerExtension,Rails会寻找一个文件名为lister_extension.rb-不是lister.rb。它很聪明,但它并不那么聪明。

Hope that helps!

希望有帮助!