我在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' –