![](/img/trans.png)
[英]NoMethodError undefined method '-@' NoMethodError in Controller Ruby on Rails
[英]'NoMethodError: undefined method' in Ruby on Rails Model
我正在創建一個每月定期付款的系統,因此我使用隨時隨地創建新的付款要求
問題似乎出現在我的支付模式方法中,就在這里。
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/
嘗試將其定義為類方法,即
def Payment.monthly_payment
# etc.
end
抱歉格式不正確,我在移動設備上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.