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

时间:2015-04-09 14:19:35

标签: ruby-on-rails methods model nomethoderror whenever

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

创建新的付款要求

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

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

2 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:0)

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

def Payment.monthly_payment
  # etc.
end

抱歉格式不正确,我正在使用手机。