Rails中的模型名称空间问题 [英] Model namespace issue in rails
问题描述
我在Rails 3.1中的名称空间有问题.我有一堂课,叫它一堂.
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
当我打电话给b :: a.method时,我得到了:
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.
推荐答案
在a
前面加上::
:
class b::a
def method
return ::a.method_from_a
end
end
对此(即作用域运算符)也进行了此处的解释. :
This, (i.e. the scope operator) is also explained here:
在类或模块中定义的常量可以不经修饰地访问 类或模块内的任何地方.在课程或模块之外,他们 可以使用无前缀的范围运算符
::'' 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
::''进行访问.
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.
顺便说一句,在Ruby中,类名应以大写字母开头.
By the way, in Ruby class names should start with an upper case letter.
这篇关于Rails中的模型名称空间问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!