'NoMethodError: undefined method' in Ruby on Rails Model

'NoMethodError: undefined method' in Ruby on Rails Model

我正在创建一个每月定期付款的系统,因此我正在使用 每当 gem

创建一个新的付款要求

问题似乎出在我的支付模型方法上,在这里。

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

在 cron.log 中,我得到了一个 NoMethodError,所以我尝试了 rails 控制台中的方法,但出现了同样的错误:

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

模型有问题吗?

这是付款的架构:

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

您必须使用 class 方法,而不是实例方法:

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

这样你就可以打电话给

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

而不是

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

一个有趣的link:http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

尝试将其定义为 class 方法,即

def Payment.monthly_payment
  # etc.
end

抱歉格式不正确,我在移动设备上。