[英]How to tell what class is calling a method in Ruby on Rails?
在我的Rails應用程序中,我有以下內容:
class Invoice < ActiveRecord::Base
has_many :payments
before_save :save_outstanding_amount
def save_outstanding_amount # atomic saving
self.outstanding_amount = new_outstanding_amount
end
def update_outstanding_amount # adds another SQL query
update_column(:outstanding_amount, new_outstanding_amount)
end
private
def new_outstanding_amount
total - payments.sum(&:amount)
end
end
如何使其動態化,以使第一個方法從Invoice
類的所有實例中調用,而第二個方法從其他類(例如Payment
類)的所有實例中調用?
您在這里做的事情很危險。 確保使用sql更改值,而不是設置新值。
想象以下情況:發票金額:1000 User1扣除100,但請求速度很慢。 在用戶1啟動后,User2會扣除500,然后很快就扣除。
由於您是在應用程序中執行此操作的,因此最后得到的金額為900,這是最后執行的方法。 update_counters創建一個“安全” SQL查詢。
self.class.update_counters self.id, payments.sum(&:amount)
這也解決了關於如何從兩個類中調用它們的問題。 總是像這樣更新這些列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.