rails中的模型命名空间问题
我在Rails 3.1中遇到了名称空间问题。 我有一节课,我们称之为。
#/app/models/a.rb class a #some methods def self.method_from_a #does things end end
但是我还有另一个在不同命名空间中具有相同名称的类。
#/app/models/b/a.rb class b::a def method return a.method_from_a end end
当我调用b :: a.method但我得到:
NameError: uninitialized constant b::a::a
我相信这是一个简单的解决方案,我只是错过了它。
用::
前缀a
:
class b::a def method return ::a.method_from_a end end
这个(即范围运算符)也在这里解释:
在类或模块中定义的常量可以在类或模块内的任何地方访问。 在类或模块之外,可以使用范围运算符来访问它们,
::'' 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
::'' 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
不带前缀::'' 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
::”。
顺便说一句,在Ruby类中,名称应以大写字母开头。