我正在创建一个每月进行定期付款的系统,因此我使用every 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
您必须使用类方法,而不是实例方法:
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/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句