无法将实例方法添加到 Ruby-on-Rails 模型

Cannot add instance method to a Ruby-on-Rails model

我正在尝试向我的模型之一添加新的实例方法。这是模型:

# app/models/server.rb
class Server < ActiveRecord::Base

  def self.zzz()
  end

end

这里是控制器:

class ServersController < ApplicationController

  def new
    @server = Server.new
    @server.zzz
  end

end

当我调用 new 方法时出现此错误:

undefined method `zzz' for #<Server:0x0055f64a3c4cb8>

为什么我不能通过这种方式向 Server class 添加额外的实例方法?我在 Debian stretch 系统上使用 Rails 4.2。

I am trying to add a new instance method to one of my models.

您添加了一个 class 方法,您不能在实例上调用 class 方法(在名称前用 self 声明)。您可以像这样直接调用 class 上的 #zzz 方法:

Server.zzz

或重新定义zzz为实例方法:

def zzz
end

能够在 @server 上调用它。