Ruby on Rails模型中的'NoMethodError:undefined method'

Lui*_*ver 3 methods model ruby-on-rails whenever nomethoderror

我正在创建一个每月定期付款的系统,因此我使用随时随地创建新的付款要求

问题似乎出现在我的支付模式方法中,就在这里.

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
Run Code Online (Sandbox Code Playgroud)

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

NoMethodError: undefined method `monthly_payment' for Payment (call 'Payment.connection' to establish a connection):Class
Run Code Online (Sandbox Code Playgroud)

模型有问题吗?

这是付款架构:

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
Run Code Online (Sandbox Code Playgroud)

MrY*_*iji 6

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

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
Run Code Online (Sandbox Code Playgroud)

所以你可以打电话

Payment.monthly_payment # class method
# method that can be called only on the Payment class
Run Code Online (Sandbox Code Playgroud)

并不是

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

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