Rails无法找到与Ruby类同名的模型 [英] Rails cannot find model with same name as Ruby class
问题描述
我对Ruby on Rails很新,我有一个带有Set模型的项目。这是在Rails 2.3.2。现在的问题是,它不能找到任何方法在该模型的类。例如:未定义的方法 find'for Set:Class或undefined method
errors'for#。它似乎试图找到这些方法在RubySet类,而不是我的模型类。
I'm fairly new to Ruby on Rails, and I have a project with a "Set" model. This is in Rails 2.3.2. Now the problem is that it can't find any methods on that model's class at all. For example: "undefined method find' for Set:Class" or "undefined method
errors' for #". It seems to be trying to find those methods on the Ruby "Set" class instead my model class.
如果我可以编写我的Set模型类的完全限定名称,如Module :: Set,它可能会工作,但我不知道会是什么。
It might work if I could write the fully-qualified name of my Set model class like Module::Set, but I'm not sure what that would be. (And yes, I really do want my model name Set. Anything else would be awkward in the context of my app).
有什么想法吗?
推荐答案
不要命名为Set。
交易是定义类失败,因为你试图重新定义在全局上下文中定义的Set。
The deal is that defining the class fails because you're trying to redefine 'Set' which is already defined in the global context.
class Set < ActiveRecord::Base # You are attempting to define a constant 'Set'
# here, but you can't because it already exists
你可以把你的类放在一个模块中,然后你不会得到错误,因为你将在命名空间中定义Set。
You can put your class in a module, and then you won't get the error because you'll be defining Set within a namespace.
module Custom
class Set < ActiveRecord::Base
end
end
但是,要使用你的Set类,你必须将其称为Custom :: Set。很多Rails魔法不会工作,因为它期望类名在全局上下文中定义。
However, every single time you want to use your Set class, you'll have to refer to it as Custom::Set. A lot of Rails magic won't work because it's expecting class names to be defined in the global context. You'll be monkeypatching plugins and gems left and right.
很容易给它一个不同的名字。
Far easier to just give it a different name.
class CustomSet < ActiveRecord::Base
所有的神奇功能,并且不需要修补。
All the magic works, and no monkeypatching required.
这篇关于Rails无法找到与Ruby类同名的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!