Rails 3 trouble with namespaces & custom classes (uninitialized constant)

旧巷老猫 提交于 2020-01-01 17:11:14

问题


I have a file in my Rails 3.2.11 project called app/queries/visible_discussions.rb which looks like the following:

class VisibleDiscussions
  ...
end

I'd like to namespace the query so that I can call it using something like Queries::VisibleDiscussions so I tried to do the following:

module Queries
  class VisibleDiscussions
    ...
  end
end

However, I'm getting a uninitialized constant Queries (NameError) when I try to call Queries::VisibleDiscussions from the rails console.

Any ideas?


回答1:


if you add lib to your autoload_paths then it will respect the namespacing under lib - lib/query/visible_discussions.rb

or create a new dir under app - say src and then nest your code there - app/src/query/visible_discussions.rb

i would use the 3rd style in your post for either of these, i.e.

module Query
  class VisibleDiscussions
    ...
  end
end

both of these solutions are annoying to me, there might be a way to tell rails to namespace directories under app, but i have no clue how it would be done




回答2:


Rails needs to know what directories to load (a part from the defaults). Try:

#config.application.rb
config.autoload_paths += %W(#{config.root}/queries)


来源:https://stackoverflow.com/questions/14348891/rails-3-trouble-with-namespaces-custom-classes-uninitialized-constant

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