我在Rails中構建了一個進銷存應用程序,它具有以下模型。導軌 - 進銷存應用程序
class Company < ActiveRecord::Base
has_many :clients
has_many :items
class Client < ActiveRecord::Base
belongs_to :company
class Invoice < ActiveRecord::Base
belongs_to :company
belongs_to :client
has_many :line_items
has_many :items, through: :line_items
accepts_nested_attributes_for :line_items
after_initialize :set_total
def set_total
total = 0
items.to_a.each do |item|
total += item.price * item.qty
end
self.total = total
end
class Item < ActiveRecord::Base
belongs_to :company
has_many :line_items
has_many :invoices, through: :line_items
class LineItem < ActiveRecord::Base
belongs_to :invoice
belongs_to :item
目前我能夠成功生成發票。問題是每當我更改引用生成的發票的商品價格時發票的總金額變化。
防止這種情況發生的最佳方法是什麼?發票一旦創建,我不希望對其總數進行任何更改。
感謝
你存儲在'invoice'表'total'?你能否提供'set_total'方法的實現細節。 – Dharam
@Dharam總屬性存儲在發票表中,這裏是方法'def set_total total = 0 items.to_a.each do | item | 總+ = item.price * item.qty 結束 self.total =總 end' –