“Uninitialized constant” error when including a module

自闭症网瘾萝莉.ら 提交于 2020-01-20 13:31:14

问题


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

class User < ActiveRecord::Base
  include ListerExtension

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

lib/lister.rb

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

I am using Rails v3.1.3.


回答1:


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 - not lister.rb. It's smart, but it's not that smart.

Hope that helps!



来源:https://stackoverflow.com/questions/11525350/uninitialized-constant-error-when-including-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!