'NoMethodError: undefined method' in Ruby on Rails Model

LuigiAlver picture LuigiAlver · Apr 9, 2015 · Viewed 9.5k times · Source

I am creating a system that recurring payments each month so I am creating a new payment requirement using the whenever gem

The problem seems to be in my Payment model method, which is here.

class Payment < ActiveRecord::Base
  belongs_to :client

  def monthly_payment
    clients = Client.all
    clients.each do |client|
      Payment.create(month: Date.now, client_id: client.id)
    end
  end
end

In the cron.log I was getting a NoMethodError so I tried the method in the rails console and the same error appears:

NoMethodError: undefined method `monthly_payment' for Payment (call 'Payment.connection' to establish a connection):Class

Is there something wrong with the Model?

Here is the schema of Payment:

create_table "payments", force: :cascade do |t|
 t.date     "date"
 t.string   "type"
 t.date     "month"
 t.boolean  "paid"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.integer  "client_id"
end

Answer

MrYoshiji picture MrYoshiji · Apr 9, 2015

You have to use a class method, not an instance method:

def self.monthly_payment # notice the self.
  clients = Client.all
  clients.each do |client|
    Payment.create(month: Date.now, client_id: client.id)
  end
end

So you will be able to call

Payment.monthly_payment # class method
# method that can be called only on the Payment class

And not

Payment.where(some_condition).first.monthly_payment # instance method
# method that can be called only on an instance of the Payment class

An interesting link about it: http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/