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

Viewed 166

I am trying to add a new instance method to one of my models. Here is the model:

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

  def self.zzz()
  end

end

Herre is the controller:

class ServersController < ApplicationController

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

end

When I call the new method I get this error:

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

Why can't I add an extra instance method to the Server class this way? I am using Rails 4.2 on a Debian stretch system.

1 Answers

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

You added a class method instead and you can't call a class method (declared with self before the name) on an instance. You can either call the #zzz method on the class directly like this:

Server.zzz

or redefine zzz to be an instance method:

def zzz
end

to be able to call it on @server.

Related