4
Rails的型号都具有一定内置的方法是这样的:延伸的轨道模型
Appointment.new
Appointment.find(1)
如何增加更多的方法来Appointment
?这显然不是通过向app/models/appointment.rb
添加方法来完成的。这样做会增加实例的Appointment
的方法,但我想将方法添加到Appointment
本身。我怎么做?
Rails的型号都具有一定内置的方法是这样的:延伸的轨道模型
Appointment.new
Appointment.find(1)
如何增加更多的方法来Appointment
?这显然不是通过向app/models/appointment.rb
添加方法来完成的。这样做会增加实例的Appointment
的方法,但我想将方法添加到Appointment
本身。我怎么做?
def self.some_method
#do stuff
end
马克的答案肯定是正确的,但你也将看到下面的语法定义类方法时:
class Appointment
class << self
def method1
# stuff
end
def method2
# stuff
end
def method3
# stuff
end
end
end
顺便说一句,你要寻找的术语是“类方法”(而不是“实例方法”)。 – ryeguy 2011-01-08 21:49:40
好的,谢谢。我想知道那是什么。 – 2011-01-09 00:54:03
`MyClass.new`是你如何启动一个标准的Ruby类实例btw,它与Rails无关。 – 2011-01-09 02:23:04