2016-02-23 102 views
0

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

目前我能夠成功生成發票。問題是每當我更改引用生成的發票的商品價格時發票的總金額變化。

防止這種情況發生的最佳方法是什麼?發票一旦創建,我不希望對其總數進行任何更改。

感謝

+0

你存儲在'invoice'表'total'?你能否提供'set_total'方法的實現細節。 – Dharam

+0

@Dharam總屬性存儲在發票表中,這裏是方法'def set_total total = 0 items.to_a.each do | item | 總+ = item.price * item.qty 結束 self.total =總 end' –

回答

0

您可以使用new_record?方法,

after_initialize :set_total 
 

 
    def set_total 
 
    total = 0 
 
    items.to_a.each do |item| 
 
     total += item.price * item.qty 
 
    end 
 
    self.total = total if self.new_record? 
 
    end

0

after_initialize被調用時,都在初始化一個新的記錄,以及同時取出由數據庫中的記錄。

您可能希望使用before_create來代替after_initialize,這樣總計只會在before_creating中設置一次,並且在每次初始化記錄時都不會更新。

你也可以簡化set_total方法如下:

def set_total 
    self.total = items.inject(0) { |sum, item| sum + (item.price * item.qty) } 
end 

參考Enumerable#inject關於注入更多的信息。

+0

嗨@Dharam,我也嘗試這種方式,由於某種原因,總的是正確的,現在保存爲0 ,,, –