2016-02-23 59 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 ,,, –