Model namespace issue in rails

℡╲_俬逩灬. 提交于 2020-02-05 04:13:46

问题


I am having an issue with namespaces in Rails 3.1. I have a class, let's call it a.

#/app/models/a.rb
class a
  #some methods
  def self.method_from_a
    #does things
  end
end

But I also have another class that has the same name in a different namespace.

#/app/models/b/a.rb
class b::a
  def method
    return a.method_from_a
  end
end

When I call b::a.method though I get:

NameError: uninitialized constant b::a::a

I am sure it is a simple solution, I am just missing it.


回答1:


Prefix a with :::

class b::a
  def method
    return ::a.method_from_a
  end
end

This, (i.e. the scope operator) is also explained here:

Constants defined within a class or module may be accessed unadorned anywhere within the class or module. Outside the class or module, they may be accessed using the scope operator, ::'' prefixed by an expression that returns the appropriate class or module object. Constants defined outside any class or module may be accessed unadorned or by using the scope operator::'' with no prefix.

By the way, in Ruby class names should start with an upper case letter.



来源:https://stackoverflow.com/questions/8969240/model-namespace-issue-in-rails

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